我正在研究ASP.NET MVC应用程序的上传脚本。我有一个与一个文件一起工作的实现,但我想扩展这个来处理多个上传。原来这里是实现:Ajax上传多个文件的脚本,jQuery ASP.NET MVC
上传视图(是的,我会动这个jQuery代码到它自己的文件):
<script type="text/javascript">
var fieldCount = 0;
function addField() {
var name = 'file' + fieldCount;
var row = 'row' + fieldCount;
var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(\'#' + row + '\'); return false;">[-]</a></label></p>';
fieldCount++;
$("#fields").append(str);
};
function removeRow(id) {
if ($("#fields").children().size() > 1) {
$(id).remove();
}
};
$(function() {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function() {
$("#resultBox").show();
$("#status").html('<h1><img src="/Content/busy.gif" /> Uploading file...</h1>');
},
success: function(result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
var tcolor;
var msg;
if (!result.message) {
tcolor = "red";
msg = result.error;
}
else {
tcolor = "green";
msg = result.message;
}
$("#resultBox").show();
$("#status").html('<span style="color:' + tcolor + ';">' + msg + '</span>').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() {
$("#resultBox").hide();
});
},
error: function(xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$("#resultBox").add("p").attr("id", "status").css("margin-top", "15px").css("padding", "20px");
$("#status").html('<span style="color:red;">Error uploading file</span>').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() {
$("#resultBox").hide();
});
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset id="uploadFields">
<legend>Upload a file</legend>
<div id="fields"></div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
<a onclick="addField(); return false;" id="add">Add</a>
<div id="resultBox">
<p id="status" style="margin:10px;"></p>
</div>
</form>
行动结果:
public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
{
Upload fileToUpload;
try
{
fileToUpload = new Upload
{
filename = file.FileName,
filesize = file.ContentLength,
date = DateTime.Now,
id = Guid.NewGuid()
};
var savedFileName = Server.MapPath(Path.Combine(@"~/uploads", Path.GetFileName(fileToUpload.filename)));
if (System.IO.File.Exists(savedFileName))
{
throw new Exception(string.Format("The file '{0}' already exists on the server.", file.FileName));
}
file.SaveAs(savedFileName);
}
catch (Exception ex)
{
return new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", ex.Message), message = string.Empty } };
}
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully. (id:{1})", Path.GetFileName(file.FileName), fileToUpload.id) } };
}
我使用的概念from this blog post获得这整个事情在滚动。
现在用我的javascript添加/删除领域,我稍微改变了行动结果:
public List<FileUploadJsonResult> AjaxUpload(HttpPostedFileBase fileBase)
{
var results = new List<FileUploadJsonResult>();
try
{
if (Request.Files.Count > 0)
{
Upload uploadFile;
for (var i = 0; i <= (Request.Files.Count - 1); i++)
{
HttpPostedFileBase file = Request.Files[i];
uploadFile = new Upload
{
filename = file.FileName,
filesize = file.ContentLength,
date = DateTime.Now,
id = Guid.NewGuid()
};
var savedFileName = Server.MapPath(Path.Combine(@"~/uploads", Path.GetFileName(uploadFile.filename)));
if (System.IO.File.Exists(savedFileName))
{
results.Add(new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", string.Format("The file '{0}' already exists on the server.", file.FileName)), message = string.Empty } });
}
file.SaveAs(savedFileName);
results.Add(new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully", file.FileName) } });
}
}
}
catch (Exception ex)
{
results.Add(new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", ex.Message), message = string.Empty } });
}
return results;
}
我有点停留在这一点上。上传工作正常,但我的JavaScript错误,因为我返回一个列表,而不是一个单一的项目。我想如果我调整代码的一部分遍历结果列表,这可以完成。
我希望能够做的另一件事是在每个文件完成上传之后,将成功文本添加到resultBox。
任何援助将不胜感激!谢谢!
对于脚本,我在的地方正常工作,我必须有HttpPostedFileBase作为参数。在原始实现中,您会看到代码中使用了参数。在多文件实现中,我使用Request.Files,所以我可以处理每个文件。 – Anders 2009-09-23 20:36:32
嗨安德斯,我看到它用于你的原始实现,但不是在你的多文件实现。你可以改变你的js分别加载每个文件并使用原始实现...? – 2009-09-24 08:08:41
我不完全确定如何去做你所建议的。据我所知,JavaScript只处理提交表单并将表单数据转储到隐藏的iframe中,以便可以异步提交表单。我对js很生疏,我刚刚开始回到事物的摆动中。任何建议或我可以尝试的东西?谢谢! – Anders 2009-09-24 18:04:37