【发布时间】:2013-03-06 09:13:13
【问题描述】:
我正在使用https://github.com/blueimp/jQuery-File-Upload,我能够将文件上传并保存到指定文件夹,然后返回 Json 对象。然后浏览器(我使用 IE8)弹出“文件下载”对话框并要求我下载一个名为“upload75bea5a4”且没有扩展名的文件。我就是想不通是哪里出了问题?
【问题讨论】:
标签: jquery-plugins asp.net-mvc-3
我正在使用https://github.com/blueimp/jQuery-File-Upload,我能够将文件上传并保存到指定文件夹,然后返回 Json 对象。然后浏览器(我使用 IE8)弹出“文件下载”对话框并要求我下载一个名为“upload75bea5a4”且没有扩展名的文件。我就是想不通是哪里出了问题?
【问题讨论】:
标签: jquery-plugins asp.net-mvc-3
我使用的是同一个插件,它对我来说没有任何问题。我将发布我正在使用的代码,以便为您提供帮助。我在Scott Hanselman's blog 看到的 C# 代码(我做了一些更改)。
用于存储文件属性的类:
public class ViewDataUploadFilesResult
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
上传代码,由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) + "\"}";
}
创造魔法的 javascript 片段:
$('#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>');
}
});
看看并做一些测试。
--
编辑
【讨论】:
刚刚在常见问题解答中找到了这个。见#2 https://github.com/blueimp/jQuery-File-Upload/wiki/Frequently-Asked-Questions
要点是当 HTTP_ACCEPT 标头不存在或不包含“application/json”时将 content-type 设置为 text/plain(在 xhr 上传时推断 iframe)。
D. Sousa 对 enctype="multipart/form-data" 的提醒 +1 - 我遇到了这个问题以及内容类型。
【讨论】:
我有同样的问题。对于 .Net,用于检查 MVC 中返回的内容类型的代码如下所示:
if (Request.ServerVariables["HTTP_ACCEPT"] != null && Request.ServerVariables["HTTP_ACCEPT"].Contains("application/json"))
{
return Json(data, "application/json");
}
else
{
return Json(data, "text/plain");
}
显然 IE 不喜欢Content-type: text/plain,而是喜欢text/plain。
希望这可以让人们更加头痛。
【讨论】: