using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using System.Threading.Tasks;using System.IO;using System.Text;namespace WebApiUpload.Controllers{ public class FileController : ApiController { //public HttpResponseMessage PostFile() //{ // HttpRequestMessage request = this.Request; // string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); // StringBuilder sb = new StringBuilder(); // var provider = new RenamingMultipartFormDataStreamProvider(root); // var task = Request.Content.ReadAsMultipartAsync(provider); // //task.Wait(); // foreach (var data in provider.FormData) // { // sb.Append(string.Format("form data: {0} ({1})\n",data.GetType(),data.ToString())); // } // foreach (var file in provider.FileData) // { // string localfilename= "big" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg"; // FileInfo fileInfo = new FileInfo(localfilename); // sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length)); // } // return new HttpResponseMessage() // { // Content = new StringContent(sb.ToString()) // }; //} //public TaskPostFile() //{ // HttpRequestMessage request = this.Request; // string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); // //var provider = new MultipartFormDataStreamProvider(root);//原写法 // var provider = new RenamingMultipartFormDataStreamProvider(root);//重命名写法 // //provider.BodyPartFileNames.sel(kv => kv.Value) // var formprovider = new RenamingMultipartFormDataStreamProvider(root);//重命名写法 // string file1 = ""; // foreach (var key in provider.FormData.AllKeys) // { // file1 = file1 + key + provider.FormData[key]; // } // var task = request.Content.ReadAsMultipartAsync(provider). // ContinueWith (o => // { // file1 = file1+ provider.GetLocalFileName(provider.FileData[0].Headers); // //多张图片循环provider.BodyPartFileNames或provider.FileData // //string file1 = provider.GetLocalFileName(provider.FileData[0].Headers);//返回重写的文件名(注意,由于packages包版本的不同,用BodyPartFileNames还是FileData需要留意) // // this is the file name on the server where the file was saved // return new HttpResponseMessage() // { // Content = new StringContent("File uploaded." + file1 ) // }; // } // ); // return task; //} [HttpPost] public async Task > PostFile() { //if (!Request.Content.IsMimeMultipartContent()) //{ // throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); //} Dictionary dic = new Dictionary (); string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");//指定要将文件存入的服务器物理位置 var provider = new RenamingMultipartFormDataStreamProvider(root); //try //{ // // Read the form data. // await Request.Content.ReadAsMultipartAsync(provider); // // This illustrates how to get the file names. // foreach (MultipartFileData file in provider.FileData) // { // Trace.WriteLine(provider.GetLocalFileName(file.Headers));//获取上传文件实际的文件名 // ///Trace.WriteLine("Server file path: " + file.LocalFileName);//获取上传文件在服务上默认的文件名 // }//TODO:这样做直接就将文件存到了指定目录下,暂时不知道如何实现只接收文件数据流但并不保存至服务器的目录下,由开发自行指定如何存储,比如通过服务存到图片服务器 // StreamWriter sw = File.AppendText("D:\\test.txt"); // foreach (var key in provider.FormData.AllKeys) // { //接收FormData // sw.Write(key + "," + provider.FormData[key] + ";"); // // dic.Add(key, provider.FormData[key]); // } // sw.Close(); //} //catch //{ // throw; //} var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith (t => { if (t.IsFaulted || t.IsCanceled) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } StreamWriter sw = File.AppendText("D:\\test.txt"); foreach (var key in provider.FormData.AllKeys) { //接收FormData sw.Write(key + "," + provider.FormData[key] + ";"); // dic.Add(key, provider.FormData[key]); } sw.Close(); // This illustrates how to get the file names. // 以下描述了如何获取文件名 foreach (MultipartFileData file in provider.FileData) { Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); }); return dic; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.IO;public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider{ public string Root { get; set; } //public FuncOnGetLocalFileName { get; set; } public RenamingMultipartFormDataStreamProvider(string root) : base(root) { Root = root; } public override string GetLocalFileName(HttpContentHeaders headers) { string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes. if (filePath.StartsWith(@"""") && filePath.EndsWith(@"""")) filePath = filePath.Substring(1, filePath.Length - 2); var extension = Path.GetExtension(filePath); string filename = "big" + DateTime.Now.ToString("yyyyMMddHHmmssff") + extension; var contentType = headers.ContentType.MediaType; return filename; }}