WebApi2 file image upload and download functions,
Asp. Net Framework webapi2 file upload and download front-end interface is executed in Ajax Mode
I. project structure
1. Cross-origin access is configured for App_Start to prevent the request from being submitted due to cross-origin issues. The specific cross-origin configuration method is as follows. If you know more about cross-origin, skip this step.
Cross-origin configuration: Install dll Microsofg. AspNet. Cors in NewGet
Then, write the cross-origin configuration code in WebApiConfig. cs under the App_Start folder.
Public static class WebApiConfig {public static void Register (HttpConfiguration config) {// Web API configuration and services // Web API routes config. mapHttpAttributeRoutes (); // Web API configuration and services // cross-origin configuration // need reference from nuget config. enableCors (new enablecorsattricors ("*", "*", "*"); config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); // if config the global filter input there need not write the attributes // config. filters. add (new App. webApi. filters. predictionattribute_dg ());}}
If cross-origin is complete, test it on your own.
2. create two controllers, one PicturesController. cs, A FilesController. cs, of course, images are files. Here, images and files are processed in different ways. Because the Image Upload method is not successful, you can find another way. If there is a better way, please kindly advise!
Ii. project code
1. Let's talk about the image upload and download controller interfaces. There is nothing to say here. Just Get the file, the parameter is the full name of the file, Post the file, and directly upload the code.
using QX_Frame.App.WebApi;using QX_Frame.FilesCenter.Helper;using QX_Frame.Helper_DG;using QX_Frame.Helper_DG.Extends;using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;using System.Web.Http;/** * author:qixiao * create:2017-5-26 16:54:46 * */namespace QX_Frame.FilesCenter.Controllers{ public class PicturesController : WebApiControllerBase { //Get : api/Pictures public HttpResponseMessage Get(string fileName) { HttpResponseMessage result = null; DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Pictures"); FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault(); if (foundFileInfo != null) { FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(fs); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name; } else { result = new HttpResponseMessage(HttpStatusCode.NotFound); } return result; } //POST : api/Pictures public async Task<IHttpActionResult> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new Exception_DG("unsupported media type", 2005); } string root = IO_Helper_DG.RootPath_MVC; IO_Helper_DG.CreateDirectoryIfNotExist(root + "/temp"); var provider = new MultipartFormDataStreamProvider(root + "/temp"); // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); List<string> fileNameList = new List<string>(); StringBuilder sb = new StringBuilder(); long fileTotalSize = 0; int fileIndex = 1; // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { //new folder string newRoot = root + @"Files/Pictures"; IO_Helper_DG.CreateDirectoryIfNotExist(newRoot); if (File.Exists(file.LocalFileName)) { //new fileName string fileName = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); string newFileName = Guid.NewGuid() + "." + fileName.Split('.')[1]; string newFullFileName = newRoot + "/" + newFileName; fileNameList.Add($"Files/Pictures/{newFileName}"); FileInfo fileInfo = new FileInfo(file.LocalFileName); fileTotalSize += fileInfo.Length; sb.Append($" #{fileIndex} Uploaded file: {newFileName} ({ fileInfo.Length} bytes)"); fileIndex++; File.Move(file.LocalFileName, newFullFileName); Trace.WriteLine("1 file copied , filePath=" + newFullFileName); } } return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully! Details -> {sb.ToString()}", fileNameList, fileNameList.Count)); } }}
Some code may be written in the Helper help class. In fact, it is only used to obtain the server root path and create a directory if the folder does not exist. The implementation of these two codes is as follows:
public static string RootPath_MVC { get { return System.Web.HttpContext.Current.Server.MapPath("~"); } }//create Directory public static bool CreateDirectoryIfNotExist(string filePath) { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } return true; }
2. The file upload/download interface is similar to the Image Upload/download interface.
using QX_Frame.App.WebApi;using QX_Frame.FilesCenter.Helper;using QX_Frame.Helper_DG;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;using System.Web;using System.Web.Http;/** * author:qixiao * create:2017-5-26 16:54:46 * */namespace QX_Frame.FilesCenter.Controllers{ public class FilesController : WebApiControllerBase { //Get : api/Files public HttpResponseMessage Get(string fileName) { HttpResponseMessage result = null; DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Files"); FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault(); if (foundFileInfo != null) { FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(fs); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name; } else { result = new HttpResponseMessage(HttpStatusCode.NotFound); } return result; } //POST : api/Files public async Task<IHttpActionResult> Post() { //get server root physical path string root = IO_Helper_DG.RootPath_MVC; //new folder string newRoot = root + @"Files/Files/"; //check path is exist if not create it IO_Helper_DG.CreateDirectoryIfNotExist(newRoot); List<string> fileNameList = new List<string>(); StringBuilder sb = new StringBuilder(); long fileTotalSize = 0; int fileIndex = 1; //get files from request HttpFileCollection files = HttpContext.Current.Request.Files; await Task.Run(() => { foreach (var f in files.AllKeys) { HttpPostedFile file = files[f]; if (!string.IsNullOrEmpty(file.FileName)) { string fileLocalFullName = newRoot + file.FileName; file.SaveAs(fileLocalFullName); fileNameList.Add($"Files/Files/{file.FileName}"); FileInfo fileInfo = new FileInfo(fileLocalFullName); fileTotalSize += fileInfo.Length; sb.Append($" #{fileIndex} Uploaded file: {file.FileName} ({ fileInfo.Length} bytes)"); fileIndex++; Trace.WriteLine("1 file copied , filePath=" + fileLocalFullName); } } }); return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully! Details -> {sb.ToString()}", fileNameList, fileNameList.Count)); } }}
After implementing the above two controller codes, we need the front-end code to debug and dock. The Code is as follows.
<! Doctype>
So far, all our functions have been implemented. Let's test it below:
It can be seen that the file is successfully uploaded and returned in the expected format!
Next we will test uploading a single image->
Then we access the image address based on the returned address.
No pressure found!
Next we will test multiimage upload->
Perfect ~
So far, we have implemented all the functions of uploading and downloading WebApi2 files and images.
Note the total size supported by the Web. config configuration for uploading files. Here I configure the maximum size of supported files to 1 MB.
<requestFiltering> <requestLimits maxAllowedContentLength="1048576" /></requestFiltering> <system.webServer>
The above section describes the WebApi2 file upload and download functions. I hope they will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!