如何让 jQuery 的 Uploadify 插件与 ASP.NET MVC 一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1002680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get jQuery's Uploadify plugin to work with ASP.NET MVC?
提问by KingNestor
I'm in the process of trying to get the jQuery plugin, Uploadify, to work with ASP.NET MVC.
我正在尝试让 jQuery 插件Uploadify与 ASP.NET MVC 一起使用。
I've got the plugin showing up fine with the following JavaScript snippet:
我已经使用以下 JavaScript 代码段使插件正常显示:
<script type="text/javascript">
$(document).ready(function() {
$('#fileUpload').fileUpload({
'uploader': '/Content/Flash/uploader.swf',
'script': '/Placement/Upload',
'folder': '/uploads',
'multi': 'true',
'buttonText': 'Browse',
'displayData': 'speed',
'simUploadLimit': 2,
'cancelImg': '/Content/Images/cancel.png'
});
});
</script>
Which seems like all is well in good. If you notice, the "script" attribute is set to my /Placement/Upload, which is my Placement Controller and my Upload Action.
这似乎一切都很好。如果您注意到,“脚本”属性设置为我的 /Placement/Upload,即我的放置控制器和上传操作。
The main problem is, I'm having difficulty getting this action to fire to receive the file. I've set a breakpoint on that action and when I select a file to upload, it isn't getting executed.
主要问题是,我很难触发此操作以接收文件。我在该操作上设置了一个断点,当我选择要上传的文件时,它没有被执行。
I've tried changing the method signature based off this article:
我已经尝试根据这篇文章更改方法签名:
public string Upload(HttpPostedFileBase FileData)
{
/*
*
* Do something with the FileData
*
*/
return "Upload OK!";
}
But this still doesn't fire.
但这仍然不会触发。
Can anyone help me write and get the Upload controller action's signature correctly so it will actually fire? I can then handle dealing with the file data myself. I just need some help getting the method action to fire.
任何人都可以帮助我正确编写并获取上传控制器操作的签名,以便它实际上会触发吗?然后我可以自己处理文件数据。我只需要一些帮助来触发方法操作。
采纳答案by Justin
public string Upload(HttpPostedFileBase FileData) {}
is correct - the file uploaded by uploadify will get binded to FileData. No need to get into Request.Files to retrieve the file - which makes it harder to mock and test.
是正确的——uploadify 上传的文件将绑定到 FileData。无需进入 Request.Files 来检索文件 - 这使得模拟和测试变得更加困难。
If your action isn't firing at all (i.e. try debugging and see if a breakpoint within the method is hit), then your issue is most likely the 'script' value - are you running under a virtual directory? If so you'll need to put the name of the directory in front. Uploadify is using an absolute path.
如果您的操作根本没有触发(即尝试调试并查看方法中的断点是否被命中),那么您的问题很可能是“脚本”值 - 您是否在虚拟目录下运行?如果是这样,您需要将目录的名称放在前面。Uploadify 使用的是绝对路径。
i.e. 'script: '/virtual_directory/Placement/Upload'
即'脚本:'/virtual_directory/Placement/Upload'
right now uploadify is sending to http://localhost/Placement/Upload.
现在 uploadify 正在发送到http://localhost/Placement/Upload。
also try using the route debugger (http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx) to check where your route is being mapped to.
还可以尝试使用路由调试器 ( http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx) 来检查路由被映射到的位置。
回答by dp.
The problem might be that you need to specify that the action you are uploading to is set to Post...it won't work with the action as a Get action.
问题可能是您需要指定您要上传到的操作设置为发布...它不能将操作作为获取操作使用。
So, this:
所以这:
public string Upload(HttpPostedFileBase FileData)
{
//do something
}
Should be this:
应该是这样的:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(HttpPostedFileBase FileData)
{
//do something
}
Also, be aware that if you are using this in a "logged in" section of your site, you should take a look here for a known bug with uploadify and authentication: http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
另外,请注意,如果您在网站的“登录”部分使用它,您应该在此处查看上传和身份验证的已知错误:http://geekswithblogs.net/apopovsky/archive/2009/ 05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
Also, just an aside, there are several ways in MVC to handle file uploads (using Request.Files as per Rory Fitzpatrick's suggestion, as well as passing the HttpPostedFileBase file as an argument in the action definition). It shouldn't really matter in order to get Uploadify to work.
另外,顺便说一句,MVC 中有几种方法来处理文件上传(根据 Rory Fitzpatrick 的建议使用 Request.Files,以及将 HttpPostedFileBase 文件作为参数传递到操作定义中)。为了让 Uploadify 正常工作,这并不重要。
回答by James McCormack
My full solution to this might solve your problem. Hope it helps.
我对此的完整解决方案可能会解决您的问题。希望能帮助到你。
http://zootfroot.blogspot.com/2010/12/mvc-file-upload-using-uploadify-with.html
http://zootfroot.blogspot.com/2010/12/mvc-file-upload-using-uploadify-with.html
回答by roryf
This isn't how I had to implement file upload at all. I had an action method with no parameters that used the current Request object to dive into the collection of posted files.
这根本不是我必须实现文件上传的方式。我有一个没有参数的 action 方法,它使用当前的 Request 对象深入到已发布文件的集合中。
Some sample code from my implementation:
我的实现中的一些示例代码:
[AcceptVerbs(HttpVerbs.Post)]
public ContentResult Upload() {
if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
HttpPostedFileBase postedFile = Request.Files[0];
// Do something with it
}
}
Of course, writing tests for this becomes a PITA. You have to mock several objects in order to get it to work, for example:
当然,为此编写测试变成了 PITA。您必须模拟多个对象才能使其工作,例如:
var mockHttpContext = mocks.StrictMock<HttpContextBase>();
var mockRequest = mocks.StrictMock<HttpRequestBase>();
var postedFile = mocks.StrictMock<HttpPostedFileBase>();
var postedFileKeyCollection = mocks.StrictMock<HttpFileCollectionBase>();
mockHttpContext.Expect(x => x.Request).Return(mockRequest).Repeat.Any();
mockRequest.Expect(x => x.Files).Return(postedFileKeyCollection).Repeat.Any();
postedFileKeyCollection.Expect(x => x[0]).Return(postedFile).Repeat.Any();
postedFileKeyCollection.Expect(x => x.Count).Return(1);
postedFile.Expect(f => f.ContentLength).Return(1024);
postedFile.Expect(f => f.InputStream).Return(null);
It would be easier to create an interface into the posted files and only mock that, with a concrete implementation injected into your controller using IoC.
在发布的文件中创建一个接口并只模拟它会更容易,使用 IoC 将具体实现注入到您的控制器中。
I think this was largely based off of this post: Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
我认为这主要基于这篇文章:使用 ASP.NET MVC 实现 HTTP 文件上传,包括测试和模拟
回答by tvanfosson
Reading the documentation, it looks like it is sending an array of files. Have you tried:
阅读文档,它看起来像是在发送一个文件数组。你有没有尝试过:
public string Upload( HttpPostedFileBase[] fileData )
It's also possible that the default model binder won't work with HttpPostedFileBase and you'll either need to use Rory's mechanism or write your own model binder.
也有可能默认模型绑定器不适用于 HttpPostedFileBase,您需要使用 Rory 的机制或编写自己的模型绑定器。
回答by Aaron Cardoz
Here is my simple Razor View (The Layout master has the Javascript bundles)
这是我的简单 Razor 视图(布局大师有 Javascript 包)
@{
ViewBag.Title = "Upload Email CSV";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" src="@Url.Content("~/Scripts/Uploadify/jquery.uploadify.js")"></script>
<script type="text/javascript">
$(function () {
var uploadUrl = "@Url.Content("~/UploadFile/UploadEmailCSV/")";
var uploadSWF = "@Url.Content("~/Scripts/Uploadify/uploadify.swf")";
var uploadifyButtonImage = "@Url.Content("~/Scripts/Uploadify/uploadify.swf")";
$('#file_upload').uploadify({
'fileSizeLimit': '0',
'buttonImage': '/uploadify/browse-btn.png',
'swf': uploadSWF,
'uploader': uploadUrl,
'onUploadSuccess': function(file, data, response) {
alert('The file was saved to: ' + data);
}
});
});
</script>
<h2>Upload a comma separated list of email addresses</h2>
@using (Html.BeginForm("UploadEmailCSV", "UploadFile", FormMethod.Post, new { @class = "form-horizontal", @enctype = "multipart/form-data", @id = "frmUploadFiles" }))
{
<input type="file" name="file_upload" id="file_upload" />
}
Here is the Contoller Method
这是控制器方法
public ActionResult UploadEmailCSV()
{
var uploadedFile = Request.Files["Filedata"];
if (uploadedFile != null && uploadedFile.ContentLength > 0)
{
var filePath = Path.Combine(Server.MapPath("~/UploadedFiles"), string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(uploadedFile.FileName), DateTime.Now.Ticks, Path.GetExtension(uploadedFile.FileName)));
uploadedFile.SaveAs(filePath);
return Content(string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(uploadedFile.FileName), DateTime.Now.Ticks, Path.GetExtension(uploadedFile.FileName)));
}
return Content("Error Uploading file!");
}
Thats it!
就是这样!