Need help debugging XHR-based Ajax Image Upload with ASP.NET MVC2

我与影子孤独终老i 提交于 2019-12-03 07:28:17

The reason you are getting an empty parameter in your controller action is because this plugin doesn't send a multipart/form-data request to the server. Instead it sends application/octet-stream content type request header and it writes the file contents directly to the request stream, appending a parameter ?qqfile to the URL containing the file name. So if you want to retrieve this on the controller you will need to directly read the stream:

[HttpPost]
public ActionResult Upload(string qqfile)
{
    using (var reader = new BinaryReader(Request.InputStream))
    {
        // This will contain the uploaded file data and the qqfile the name
        byte[] file = reader.ReadBytes((int)Request.InputStream.Length);
    }
    return View();
}

If you select multiple files the plugin simply sends multiple requests to the server so this will work.

Also if you want to handle files bigger than int.MaxValue you will have to read from the request stream in chunks and write directly to an output stream instead of loading the whole file into a memory buffer:

using (var outputStream = File.Create(qqfile))
{
    const int chunkSize = 2 * 1024; // 2KB
    byte[] buffer = new byte[chunkSize];
    int bytesRead;
    while ((bytesRead = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outputStream.Write(buffer, 0, bytesRead);
    }
}

Remark: Remove the createUploader function name from your document.ready. It should be an anonymous function there. You could even merge it with the $(function() { ... }); you already have to setup the modal dialog.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!