国产99久久精品_欧美日本韩国一区二区_激情小说综合网_欧美一级二级视频_午夜av电影_日本久久精品视频

最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
當前位置: 首頁 - 科技 - 知識百科 - 正文

WebApi2 文件圖片上傳與下載功能

來源:懂視網 責編:小采 時間:2020-11-27 22:35:39
文檔

WebApi2 文件圖片上傳與下載功能

WebApi2 文件圖片上傳與下載功能:Asp.Net Framework webapi2 文件上傳與下載 前端界面采用Ajax的方式執行 一、項目結構 1.App_Start配置了跨域訪問,以免請求時候因跨域問題不能提交。具體的跨域配置方式如下,了解的朋友請自行略過。 跨域配置:NewGet安裝dll Microsofg
推薦度:
導讀WebApi2 文件圖片上傳與下載功能:Asp.Net Framework webapi2 文件上傳與下載 前端界面采用Ajax的方式執行 一、項目結構 1.App_Start配置了跨域訪問,以免請求時候因跨域問題不能提交。具體的跨域配置方式如下,了解的朋友請自行略過。 跨域配置:NewGet安裝dll Microsofg

Asp.Net Framework webapi2 文件上傳與下載 前端界面采用Ajax的方式執行

一、項目結構

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當然圖片也是文件,這里圖片和文件以不同的方式處理的,因為圖片的方式文件上傳沒有成功,所以另尋他路,如果在座的有更好的方式,請不吝賜教!

二、項目代碼

1.我們先說圖片上傳、下載控制器接口,這里其實沒什么好說的,就一個Get獲取文件,參數是文件全名;Post上傳文件;直接上代碼。

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

里面可能有部分代碼在Helper幫助類里面寫的,其實也僅僅是獲取服務器根路徑和如果判斷文件夾不存在則創建目錄,這兩個代碼的實現如下:

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

實現了上述兩個控制器代碼以后,我們需要前端代碼來調試對接,代碼如下所示。

<!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 + '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
 })
 </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>

以上所述是小編給大家介紹的WebApi2 文件圖片上傳與下載功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

WebApi2 文件圖片上傳與下載功能

WebApi2 文件圖片上傳與下載功能:Asp.Net Framework webapi2 文件上傳與下載 前端界面采用Ajax的方式執行 一、項目結構 1.App_Start配置了跨域訪問,以免請求時候因跨域問題不能提交。具體的跨域配置方式如下,了解的朋友請自行略過。 跨域配置:NewGet安裝dll Microsofg
推薦度:
  • 熱門焦點

最新推薦

猜你喜歡

熱門推薦

專題
Top
主站蜘蛛池模板: 成a人片亚洲日本久久 | 日韩一区二区久久久久久 | 欧美日韩国产亚洲人成 | 国产精品一区二区免费 | 欧美伦禁片在线播放 | 国产不卡一区二区视频免费 | 欧美精品首页 | 国产在线视频不卡 | 一级毛片免费的 | xx中文字幕乱偷avxx | 成人亚洲欧美日韩在线 | 国产在线视频专区 | 久久国产精品久久久久久久久久 | 国产精品免费观看 | 日韩欧美电影在线观看 | 日本成人一区二区 | 亚洲色图88| 亚洲 另类 在线 欧美 制服 | 亚洲韩国日本欧美一区二区三区 | 国产成人精品久久一区二区小说 | 色老头久久久久久久久久 | 亚洲欧美在线一区 | 欧美成人看片一区二区三区尤物 | 欧美成人免费高清二区三区 | 欧美亚洲一区二区三区 | 免费观看一级成人毛片 | 欧美日韩国产亚洲一区二区三区 | 欧美成人免费高清视频 | 国产网站精品 | 视频一区二区三区欧美日韩 | 亚洲综合日韩在线亚洲欧美专区 | 久久精品一区二区三区四区 | 国产人澡人澡澡澡人碰视频 | 国产精品欧美亚洲韩国日本不卡 | 国内不卡1区2区 | 中文字幕三区 | 久久国产精品高清一区二区三区 | 亚洲一区二区在线免费观看 | 日韩在线视频免费 | 欧美精品一二三 | 一区在线观看 |