Share WebApi2 file image upload and download function instances

Source: Internet
Author: User
This article mainly introduces the WebApi2 file image upload and download function, the need for friends can refer to the next





ASP. NET Framework webapi2 file upload and download the front-end interface takes the AJAX approach



I. Structure of the project






1.app_start is configured for cross-domain access so that requests cannot be submitted because of cross-domain issues. The specific cross-domain configuration is as follows, please do not know the friend to skip.



Cross-Domain Configuration: Newget Install DLL Microsofg.AspNet.Cors






The cross-domain configuration code is then written to the WebApiConfig.cs in 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 completed, please test it yourself.

2. Create two new controllers, one PicturesController.cs and one FilesController.cs. Of course, pictures are also files. Here pictures and files are processed in different ways. Because the uploading of files by pictures is not successful, so find another way, if you are here There is a better way, please let me know!

Second, the project code

1. Let's talk about image uploading and downloading the controller interface first. In fact, there is nothing to say here. Get a file with a Get, the parameter is the full name of the file; Post uploads the file; 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));
    }
  }
}
There may be some code written in the Helper class. In fact, it is only 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. File upload and download interfaces are similar to pictures.



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 front-end code to debug the docking, the code is shown below.



<! doctype>
<head>
  <script src = "jquery-3.2.0.min.js"> </ script>
  <!-<script src = "jquery-1.11.1.js"> </ script>->
  <!-<script src = "ajaxfileupload.js"> </ script>->
  <script>
    $ (document) .ready (function () {
      var appDomain = "http: // localhost: 3997 /";
      $ ("# btn_fileUpload"). click (function () {
        / **
         * Upload files with 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
        / **
         * Upload files with 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
    })
  </ script>
</head>
<title> </ title>
<body>
  <article>
    <header>
      <h2> article-form </ h2>
    </ header>
    <p>
      <form action = "/" method = "post" id = "uploadForm" enctype = "multipart / form-data">
        <Input type = "file" id = "files" name = "files" placeholder = "file" multiple> file-multiple attributes can choose a number of <br> <br>
        <input type = "button" id = "btn_fileUpload" value = "fileUpload">
      </ form>
    </ p>
  </ article>
</ body>
So far, our functions have been fully implemented, let's test it below:

It can be seen that the file is uploaded successfully and returned in the expected format!

Below we test single picture upload->

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

Found no pressure!

The following test multi-image upload->

Perfect ~

So far, we have implemented all functions of WebApi2 file and image upload and download.

Here we need to pay attention to the total size supported by the configuration upload file of Web.config. The maximum supported file size is 1MB.

<requestFiltering>
  <requestLimits maxAllowedContentLength = "1048576" />
</ requestFiltering>
  <system.webServer>
   <handlers>
    <remove name = "ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name = "OPTIONSVerbHandler" />
    <remove name = "TRACEVerbHandler" />
    <add name = "ExtensionlessUrlHandler-Integrated-4.0" path = "*." verb = "*" type = "System.Web.Handlers.TransferRequestHandler" preCondition = "integratedMode, runtimeVersionv4.0" />
   </ handlers>
   <security>
   <requestFiltering>
    <requestLimits maxAllowedContentLength = "1048576" /> <!-1MB->
    </ requestFiltering>
  </ security>
  </system.webServer>
【related suggestion】

1. ASP.NET free video tutorial

2. A detailed introduction to ASP.NET MVC-routing

3. Introduce ASP.NET MVC-controller in detail

4. A detailed introduction to ASP.NET MVC-View

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.