ホームページ  >  記事  >  バックエンド開発  >  WebApi2ファイル共有と画像アップロード・ダウンロード機能例

WebApi2ファイル共有と画像アップロード・ダウンロード機能例

零下一度
零下一度オリジナル
2017-05-31 13:59:234310ブラウズ

この記事では、主に WebApi2 のファイルと画像のアップロードとダウンロードの機能を紹介します。必要な友達は、

Asp.Net Framework webapi2 を参照してください。ファイルのアップロードとダウンロード フロントエンド インターフェイスは Ajax メソッドで実行されます

1. プロジェクト構造

1.App_Start は、クロスドメインの問題により送信できないリクエストを回避するために、クロスドメイン アクセスを使用して構成されています。具体的なクロスドメイン設定方法は以下の通りですが、ご存知の方はご自身で読み飛ばしてください。

クロスドメイン構成: NewGet は DLL Microsofg.AspNet.Cors をインストールします

次に、App_Start フォルダーの下の WebApiConfig.cs にクロスドメイン構成コードを書き込みます。

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
      //跨域配置 //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());
    }
  }

クロスドメインが完了しても、ご自身でテストしてください。

2. PicturesController.cs と FilesController.cs の 2 つの新しいコントローラーを作成します。もちろん、写真とファイルは別の方法で処理されます。別の方法を見つけました。誰かがより良い方法を持っている場合は、遠慮なく教えてください。

2. プロジェクト コード

1. まず、画像のアップロードとダウンロードのコントローラー インターフェイスについて説明します。実際には、ここで言うことは何もありません。ファイルを取得するための Get だけです。パラメーターはファイルのフルネームです。 file; ファイルをアップロードするには、コードを直接入力します。


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(&#39;.&#39;)[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));
    }
  }
}

Helpクラスにはいくつかのコードが書かれているかもしれませんが、実際には、この2つのコードの実装は、サーバーのルートパスを取得し、フォルダーが存在しないと判断された場合にディレクトリを作成するだけです。


 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. ファイルのアップロードおよびダウンロードのインターフェースは写真のインターフェースと似ています。


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));
    }
  }
}

上記の 2 つのコントローラー コードを実装した後、接続を デバッグするためのフロントエンド コードが必要です。コードは次のとおりです。


<!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 () {
        /**
         * 用ajax方式上传文件  -----------
         * */
        //-------asp.net webapi fileUpload
        //
        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({
          url: appDomain + &#39;api/Files&#39;,
          type: &#39;POST&#39;,
          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+&#39;api/Files&#39;,
        //   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: &#39;post&#39;,
        //   url: appDomain + &#39;api/Files&#39;,
        //   secureuri: false,
        //   fileElementId: &#39;files&#39;,
        //   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属性可以选择多项<br><br>
        <input type="button" id="btn_fileUpload" value="fileUpload">
      </form>
    </p>
  </article>
</body>

この時点で、すべての関数が実装されているので、テストしてみましょう:

ファイルが正常にアップロードされ、予期した形式で返されたことがわかります。

次に、単一の画像のアップロードをテストします ->

次に、返されたアドレスを押して画像アドレスにアクセスします。

全然プレッシャーがないことが分かりました!

以下で複数の画像アップロードをテストします ->

完璧~

この時点で、WebApi2 ファイルと画像のアップロードとダウンロードのすべての機能が実装されました。

ここで、Web.config 構成アップロード ファイルでサポートされる合計サイズに注意する必要があります。ここで構成したのは、サポートされる最大ファイル サイズが 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>

[関連推奨事項]

1。無料のビデオチュートリアル

2. ASP.NET MVC の詳細な紹介 - ルーティング

3. ASP.NET MVC の詳細な紹介 - コントローラー

4. MVC -- 表示

以上がWebApi2ファイル共有と画像アップロード・ダウンロード機能例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。