Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of uploading and downloading File Pictures with WebApi2

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces WebApi2 how to achieve file picture upload and download function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand.

I. Project structure

1.App_Start is configured with cross-domain access to prevent requests from being submitted due to cross-domain issues. The specific cross-domain configuration is as follows. For those who know it, please skip it.

Cross-domain configuration: NewGet installs dll Microsofg.AspNet.Cors

Then write the cross-domain configuration code in the 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-domain configuration / / need reference from nuget config.EnableCors (new EnableCorsAttribute ("*", "*", "*") 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.ExceptionAttribute_DG ());}}

Even if the cross-domain is complete, please test it yourself.

two。 Two new controllers, one PicturesController.cs, one FilesController.cs, of course, the picture is also a file, here the picture and the file are processed in different ways, because the file upload is not successful, so find another way, if there is a better way, please do not hesitate to comment!

II. Project code

1. Let's first talk about the interface of the controller for uploading and downloading images. There is nothing to say here, just a Get to obtain the file, and the parameter is the full name of the file; Post to upload the file; and code directly.

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 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 fileNameList = new List (); 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 of the code may be written in the Helper help class, but it only obtains the server root path and creates a directory if it is determined that 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;}

two。 The file upload and download interface is more or less the same as the picture.

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 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 fileNameList = new List (); 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 code, we need the front-end code to debug the docking, as shown below.

$(document) .ready (function () {var appDomain = "http://localhost:3997/"; $("# btn_fileUpload") .click (function () {/ * upload the file by ajax-* /-asp.net webapi fileUpload / / var formData = new FormData ($("# uploadForm") [0]) $.ajax ({url: appDomain + 'api/Files', type:' POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) {console.log (JSON.stringify (data)) }, error: function (data) {console.log (JSON.stringify (data));}}); / /-end asp.net webapi fileUpload / /--. Net core webapi fileUpload / / var fileUpload = $("# files"). Get (0); / / var files = fileUpload.files; / / var data = new FormData () / / for (var I = 0; I

< files.length; i++) { // data.append(files[i].name, files[i]); // } // $.ajax({ // type: "POST", // url: appDomain+'api/Files', // contentType: false, // processData: false, // data: data, // success: function (data) { // console.log(JSON.stringify(data)); // }, // error: function () { // console.log(JSON.stringify(data)); // } // }); //--------end net core webapi fileUpload /** * ajaxfileupload.js 方式上传文件 * */ // $.ajaxFileUpload({ // type: 'post', // url: appDomain + 'api/Files', // secureuri: false, // fileElementId: 'files', // success: function (data) { // console.log(JSON.stringify(data)); // }, // error: function () { // console.log(JSON.stringify(data)); // } // }); }); //end click }) article-form file-multiple属性可以选择多项 至此,我们的功能已全部实现,下面我们来测试一下: 可见,文件上传成功,按预期格式返回! 下面我们测试单图片上传->

Then we access the picture address according to the returned address.

Found that there is no pressure!

Let's test multiple image uploads->

Perfect ~

So far, we have achieved all the functions of uploading and downloading WebApi2 files and pictures.

You need to pay attention to the total size supported by the Web.config configuration upload file. What I configure here is that the maximum supported file size is 1MB.

Thank you for reading this article carefully. I hope the article "how to upload and download WebApi2 files and pictures" shared by the editor will be helpful to everyone. At the same time, I also hope you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report