Use uploadify in Asp.net MVC to upload files

Source: Internet
Author: User

I. uploadify Control

In ASP. there are many upload controls in. net, such. net, including fileupload, swfupload, and uploadify. In particular, the user experience of the following two controls is better, like refreshing traffic and uploading progress. In a recent webform development project, I used uploadify. Although it has some flaws, however, it is basically satisfactory (you can refer to "jquery upload plug-in uploadify Usage Details" for using uploadify in webform). Therefore, when using MVC development, you will naturally choose it as your first choice.

 

Uploadify official demo


Ii. Use uploadify in MVC

First introduce JS and CSS files:

<script src="/Content/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Content/Scripts/swfobject.js" type="text/javascript"></script>
<script src="/Content/Scripts/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
<link href="/Content/Styles/uploadify.css" rel="stylesheet" type="text/css" />

 

Put the most common file control on the page (checkimport is a verification method written by myself. If you do not select to upload a file ):

 <Div>
<P> <input id = "fileinput1" name = "fileinput1" type = "file"/> </P>
<P style = "margin-top: 5px; font-size: 14px; font-weight: bold;"> <a href = "javascript: If (checkimport ()) {$ ('# fileinput1 '). uploadifyupload ();} "> Import file </a> </P>
<P style = "margin-top: 5px; font-size: 14px; font-weight: bold; "> <span id =" result "> </span> </P>
</Div>

 

Then you can add the following JS Code. The script is a processing address of the Request server. In webform, it usually points to An ASPX or ashx file. In MVC, it requests an action, for example, here is the import method for requesting excelcontroller (my path is "admin/{controller}/{action}/{ID }"):

 

 $ (Function (){
// Upload
$ ('# Fileinput1'). uploadify ({
'Upload': '/content/images/uploadify.swf ',
'Script': '/admin/EXCEL/import ',
'Folder': '/uploadfiles ',
'Cancelim': '/content/images/cancel.png ',
'Fileext ':' *. xls ',
'Filedesc': '*. xls ',
'Sizelimmit ': 1024*1024*4, // 4 m
'Multi ': false,
'Oncomplete': Fun
});

});
Function fun (event, queueid, fileobj, response, data ){
If (response! = ""){
Showinfo ("successfully uploaded" + response, true); // set the upload result using the showinfo Method
}
Else {
Showinfo ("File Upload error! ", False );
}
}

 

This can be written in the corresponding excelcontroller:

 

 [Acceptverbs (httpverbs. Post)]
Public contentresult import (httppostedfilebase filedata, string folder)
{
String result = "";
If (null! = Filedata)
{
Try
{
Result = path. getfilename (filedata. filename); // get the file name
String ext = path. getextension (filedata. filename); // obtain the file extension.
String savename = "uploadfile" + ext; // the actual file name.
SaveFile (filedata, folder, savename); // save the file
}
Catch
{
Result = "";
}
}
Return content (result );
}

[Nonaction]
Private void SaveFile (httppostedfilebase postedfile, string filepath, string savename)
{
String phypath = request. mappath ("~ "+ Filepath + "/");
If (! Directory. exists (phypath ))
{
Directory. createdirectory (phypath );
}
Try
{
Postedfile. saveas (phypath + savename );
}
Catch (exception E)
{
Throw new applicationexception (E. Message );

}
}

 

Note that both the filedata and folder parameters have fixed names, and the filedata parameter type is httppostedfilebase rather than httppostedfile (I am stuck here for a long time and cannot get the file ), I found this article on the Internet about why I want to use httppostedfilebase. It seems that it is because of the unit test...

 

 Just work with it as an HttpPostedFileBase. The framework uses the HttpPostedFileWrapper  to convert an HttpPostedFile to an object of HttpPostedFileBase. HttpPostedFile is one of those sealed classes that are hard to unit test with. I suspect that sometime after the example was written they applied the wrapper code to improve the ability to test(using HttpPostedFileBase) controllers in the MVC framework. Similar things have been done with the HttpContext, HttpRequest, and HttpReponse properties on the controller.

 

 

After a file is successfully uploaded, the effect is as follows:

 

Instance program download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.