I'm using https://github.com/blueimp/jQuery-File-Upload and I was able to upload and save the file to designated folder, and then I return the Json object. Then the browser (I use IE8) pops "File Download" dialog and asks me to download a file named "upload75bea5a4" with no extension. I just could not figure out what is wr开发者_如何学JAVAong?
I am using the same plugin and it's working without any problems for me. I will post the codes I am using so that can help you. The C# code I saw at Scott Hanselman's blog (and I made few changes).
A class to store the properties of the file:
public class ViewDataUploadFilesResult
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
The upload code, which is called by the ajax:
[HttpPost]
public string UploadFiles()
{
var r = new List<ViewDataUploadFilesResult>();
Core.Settings settings = new Core.Settings();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Path.Combine(settings.StorageLocation + "\\Files\\", Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new ViewDataUploadFilesResult()
{
Name = hpf.FileName,
Length = hpf.ContentLength,
Type = hpf.ContentType
});
}
return "{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}";
}
The javascript piece which makes the magic:
$('#file_upload').fileUploadUI({
uploadTable: $('#files'),
downloadTable: $('#files'),
buildUploadRow: function (files, index) {
return $('<tr><td>' + files[index].name + '<\/td>' +
'<td class="file_upload_progress"><div><\/div><\/td>' +
'<td class="file_upload_cancel">' +
'<button class="ui-state-default ui-corner-all" title="Cancel">' +
'<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
'<\/button><\/td><\/tr>');
},
buildDownloadRow: function (file) {
return $('<tr><td>' + file.name + '<\/td><\/tr>');
}
});
Take a look and make some tests.
--
EDIT
I wrote an article about it.
Just found this in the FAQ. See #2 https://github.com/blueimp/jQuery-File-Upload/wiki/Frequently-Asked-Questions
gist is to set content-type to text/plain when HTTP_ACCEPT header does not exists or doesn't contain 'application/json' (inferring iframe on xhr upload).
+1 for D. Sousa's reminder for enctype="multipart/form-data" - I ran into that as well as the content-type.
I had the same issue. For .Net the code for checking the content type in MVC coming back looks like this:
if (Request.ServerVariables["HTTP_ACCEPT"] != null && Request.ServerVariables["HTTP_ACCEPT"].Contains("application/json"))
{
return Json(data, "application/json");
}
else
{
return Json(data, "text/plain");
}
Apparently IE does not like Content-type: text/plain
but text/plain
.
Hope this saves somebody a further headache.
精彩评论