Introduction
This article mainly introduces how to use uploadify in the Asp.net MVC project and implement simple proportional scaling and saving of images. I have sorted out some online resources for reference in this article. If you have any questions, please note.
Uploadify Introduction
The new uploadify version changes the parameters.
This document uses v3.2. If you use a previous version, refer to uploadify in Asp.net MVC to upload files. For details about uploadify, refer to the jquery upload plug-in uploadify.
Uploadify APIs:
Options
SWF: relative path of the uploadify.swf File
Uploader: relative path of the background processing program
Queueid: ID of the file queue, which is consistent with the ID of the DIV storing the file queue.
Auto: true: upload directly. If this parameter is set to false, you must call the relevant method (see upload) to upload the file.
Multi: true: Multi-File Upload is allowed; false: single-file upload is allowed.
Formdata: passing additional parameters through form
Events
Onuploadsuccess: callback function for each successful upload
Methods
Settings: returns or updates the setting attributes of an uploadify instance.
Upload: uploads a specific file or all in the file queue.
Note: cancelimgThe cancel button in this transmission picture is missing. I changed it directly in uploadify.css.
The above parameters are required by the code in this article. For other parameters, refer to the official documentation.
Use uploadify in mvc4 to introduce JS and CSS files in the header of the title
<script type="text/javascript" src="~/Scripts/jquery-2.0.0.min.js"></script><script type="text/javascript" src="~/Scripts/uploadify/jquery.uploadify.js"></script><link href="~/Scripts/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
Add control labels in view
<Div> @ HTML. label ("H:") @ HTML. textbox ("H", "", new {@ class = "intonly"}) // enter the image height to be saved as @ HTML. label ("* required an integer", new {id = "hval", style = "display: none; color: red ;"}) </div> <div> @ HTML. label ("W:") @ HTML. textbox ("W", "", new {@ class = "intonly"}) // enter the image width to be saved @ HTML. label ("* required an integer", new {id = "wval", style = "display: none; color: red ;"}) </div> <input type = "file" name = "uploadify" id = "uploadify"/> <Div id = "filequeue"> </div> // uploaded file queue display label <a href = "javascript: void (0) "id =" uploadstart "> upload files </a> // use the tag to control when to upload @ HTML. textbox ("filepath ") // Save the saved image path set <br/> // display an image. effectAdd js to the file control
$ ("# Uploadify"). uploadify ({'swf ':' @ URL. Content ("~ /Scripts/uploadify/uploadify.swf ") ', // The 'upload':' @ URL. action ("uploadify") ', // post to the internal uploadify method. note: The parameter 'queueid': 'filequee' cannot be passed as a query string, // bind the file queue ID 'auto': false, // disable automatic upload of 'multi ': true, // allow Multifile upload 'onuploadsuccess': function (file, Data, response) {var S = data; var filepath = $ ("# filepath "). val (); var filepaths = filepath + ";" + data; // concatenate the image path if (filepath. trim () = "") {// if there is only one image, use the semicolon filepaths = data;} $ ("# filepath "). val (filepaths); $ ("# fileimg "). ATTR ("src", filepaths. split (";") [0]); // display the first uploaded image }});
Note: The above Uploader parameter requests a MVC method, here is the uploadify method of the current controller (my path is the default "{controller}/{action}/{ID }");
Add verification and restrictions to pass additional parameters
$ (Function () {$ (". intonly "). keyup (function () {This. value = This. value. replace (/[^ 0-9 \.] /g, ''); // make it possible to enter only decimals and integers in the high-width input box}); $ (" # uploadstart "). click (function () {// click event that controls the uploaded a tag if ($ ("# filequeue" ).html (). trim () = "") {// verify that no file is uploaded. Alert ("Select Upload file first"); return ;} vaR H = $ ("# H "). val (); var W = $ ("# W "). val (); If (H. trim () = "") {// when the height box has no value, prompt $ ("# hval" ).css ("display", "inline"); return ;} else {$ ("# hval" ).css ("display", "NONE");} If (W. trim () = "") {// when there is no value in the width box, prompt $ ("# wval" ).css ("display", "inline"); return ;} else {$ ("# wval" ).css ("display", "NONE") ;}$ (". intonly "). ATTR ({"disabled": "true"}); // after the verification is passed, the height and width cannot be entered. $ (". intonly ").css (" background-color "," # efeeef "); $ (" # uploadify "). uploadify ('settings', 'formdata', {'H': $ ("# H "). val (), 'w': $ ("# W "). val ()}); // pass the additional parameter to Action $ ("# uploadify") by setting the formdata value of settings "). uploadify ('upload', '*'); // upload all files in the file queue // note, I didn't try to use Upload and settings as parameters at the same time });});C # proportional scaling Image Algorithm
This method is based on a foreign website (the original article link). You can only scale the image proportionally, but it is not satisfactory. If you have any better methods, please advise.
private static Image resizeImage(Image imgToResize, Size size) { int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)size.Width / (float)sourceWidth); nPercentH = ((float)size.Height / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (Image)b; }Process images in the Controller Method
[Httppost]
Public actionresult uploadify (int h = 300, int W = 300) // Note: To obtain the form value through the method parameter, the default value is required. Otherwise, the {string filepath = ""; foreach (string item in request. files) {httppostedfilebase postfile = request. files [item]; If (postfile. contentlength = 0) continue; string newfilepath = request. applicationpath + "uploadfile/" + String. format ("{0: yyyymmdd}", datetime. today); If (! System. io. directory. exists (server. mappath (newfilepath) // create the folder {system. io. directory. createdirectory (server. mappath (newfilepath);} string file = newfilepath + "/" + String. format ("{0: hhmmss}", datetime. now) + "_" + system. guid. newguid () + ". "+ postfile. filename. split ('. '). last (); filepath = file; image imagefile = resizeimage (image. fromstream (postfile. inputstream, true, true), new size {Height = H, width = w}); imagefile. save (server. mappath (File);} return content (filepath); // set the file path to response}
After completion
Conclusion
So far, the use of uploadify is over. I graduated from the physics department for almost a year, and almost a year of entry. I am working hard to learn from the experts. I have been thinking about writing a blog since I came into contact with the blog Park and saw a great guy like fish Li. This is also the first time I write a blog. If you have any questions, please correct me! Finally, I would like to thank timyang, who frequently wrote blogs, for feeling strong positive energy from his blog. Thank you for choosing this blog site.
Attachment: source code download