ASP. net mvc HttpPostedFileBase File Upload instance code,

Source: Internet
Author: User

ASP. net mvc HttpPostedFileBase File Upload instance code,

This article introduces ASP. net mvc HttpPostedFileBase file upload and shares it with you, hoping to help you

HttpPostedFileBase allows you to upload multiple files at a time. If you have images, you can save the thumbnail.

File Transfer Information Encapsulation

/// <Summary> /// file generation method /// </summary> public class UpFileMessage {// <summary> /// file name /// </summary> public string OriginalFileName {get; set ;}//< summary> /// whether to save the thumbnail // </summary> public bool IsImage {get; set ;} /// <summary> /// file Stream /// </summary> public Stream FileStream {get; set ;} /// <summary> /// method for generating the thumbnail // [WH]-specify the width and height // [H]-specify the height, proportional scaling width // [W]-specify the width and proportional scaling height /// </summary> publi C string Mode {get; set ;}/// <summary> /// scale down the Image Height // </summary> public int? ThumbHeight {get; set ;}/// <summary> /// thumbnail width /// </summary> public int? ThumbWidth {get; set ;}}

File Upload return results

/// <Summary> /// File Upload return result /// </summary> public class UpFileResultMessage {// <summary> /// check whether the file is successfully saved /// </summary> public bool IsSuccess {get; set ;}//< summary> /// error Message /// </summary> public string Message {get; set ;} /// <summary> /// original file name-(no extension) /// </summary> public string FileName {get; set ;} /// <summary> /// file name extension /// </summary> public string FileSuffix {get; set ;} /// <summary> /// file name storage path /// </summary> public string FilePath {get; set ;} /// <summary> /// when the file type is image, // the path for saving the thumbnail /// </summary> public string ThumbPath {get; set ;} /// <summary> /// save the file name (without an extension) /// </summary> public string SaveFileName {get; set ;} /// <summary> /// File Auto-increment ID /// </summary> public int [] FileIdArray {get; set ;}}

File Upload class library

You must reference the System. Web namespace and inherit from [System. Web. UI. Page] to call the Server. MapPath method.

Public class FileUtil: System. web. UI. page {// <summary> /// upload images /// </summary> /// <param name = "fileMessage"> file generation method </param> // /<returns> </returns> public UpFileResultMessage UpLoadFile (UpFileMessage fileMessage) {try {string now = DateTime. today. toString ("yyyyMMdd"); string guid = Guid. newGuid (). toString (); // obtain the file extension var fileSuffix = Path. getExtension (fileMessage. originalFileName); var uploa DFolder = Path. Combine (System. Web. HttpContext. Current. Server. MapPath (ParmsConfig. UpFilePathUrl), now); if (! Directory. exists (uploadFolder) {Directory. createDirectory (uploadFolder);} // save the file name string saveFileName = guid + fileSuffix; string filePath = Path. combine (uploadFolder, saveFileName); UpFileResultMessage upFileResult = new UpFileResultMessage () {IsSuccess = true, FileName = Path. getFileNameWithoutExtension (fileMessage. originalFileName), FileSuffix = fileSuffix, FilePath = string. format (@ "{0}/{1} ", ParmsConfig. upFileIPAddressUrl, now), SaveFileName = guid}; using (Stream sourceStream = fileMessage. fileStream) {using (FileStream targetStream = new FileStream (filePath, FileMode. create, FileAccess. write, FileShare. none) {const int bufferLen = 1024*4; // 4KB byte [] buffer = new byte [bufferLen]; int count = 0; while (count = sourceStream. read (buffer, 0, bufferLen)> 0) {targetStream. wri Te (buffer, 0, count) ;}// create a thumbnail if (fileMessage. isImage) {var uploadThumbFolder = Path. combine (uploadFolder, "Thumb"); if (! Directory. exists (uploadThumbFolder) {Directory. createDirectory (uploadThumbFolder);} using (FileStream targetStream = new FileStream (filePath, FileMode. open, FileAccess. read, FileShare. none) {System. drawing. image image = System. drawing. image. fromStream (targetStream); int width = image. width; int height = image. height; int thumbWidth = 0; int thumbHeight = 0; switch (fileMessage. mode) {case "WH ": // Specify high-width Scaling (which may be deformed) thumbWidth = fileMessage. ThumbWidth. HasValue? FileMessage. ThumbWidth. Value: 200; thumbHeight = fileMessage. ThumbHeight. HasValue? FileMessage. ThumbHeight. Value: 200; break; case "W": // specify the width. The height is proportional to thumbWidth = fileMessage. ThumbWidth. HasValue? FileMessage. ThumbWidth. Value: 200; thumbHeight = height * thumbWidth/width; break; case "H": // specify the height. The width is proportional to thumbHeight = fileMessage. ThumbHeight. HasValue? FileMessage. ThumbHeight. Value: 200; thumbWidth = width * thumbHeight/height; break; default: thumbWidth = fileMessage. ThumbWidth. HasValue? FileMessage. thumbWidth. value: 200; thumbHeight = height * thumbWidth/width; break;} string thumbFilePath = Path. combine (uploadThumbFolder, saveFileName); CreateThumbnail (thumbFilePath, targetStream, thumbWidth, thumbHeight); upFileResult. thumbPath = string. format (@ "{0}/{1}/Thumb", ParmsConfig. upFileIPAddressUrl, now) ;}} return upFileResult;} catch (Exception ex) {return new UpFileResultMessage () {IsSuccess = false, Message = ex. message };}} /// <summary> /// create a thumbnail of the specified image file stream /// </summary> /// <param name = "thumbFilePath"> saved path of the thumbnail file </ param> /// <param name = "fileStream"> original file stream </param> /// <param name = "width"> thumbnail width </param> /// <param name = "height"> thumbnail height </param> private void CreateThumbnail (string thumbFilePath, stream fileStream, int width, int height) {using (Image image = Image. fromStream (fileStream) {using (Image thumbnail = image. getThumbnailImage (width, height, null, IntPtr. zero) {thumbnail. save (thumbFilePath );}}}}

Call Method

var upFileMsg = new UpFileMessage()          {            IsImage = true,            OriginalFileName = platformImg[i].FileName,            FileStream = platformImg[i].InputStream,            ThumbWidth = ThumbWidth,            Mode = "W"          };         var  upFileResultMsg = new FileUtil().UpLoadFile(upFileMsg);

Code address: File Upload class library package. Zip

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.