博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
图片上传
阅读量:5995 次
发布时间:2019-06-20

本文共 6043 字,大约阅读时间需要 20 分钟。

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 Task
PostFile() //{ // 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 Func
OnGetLocalFileName { 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; }}

 

转载于:https://www.cnblogs.com/yes-you-can/p/5241404.html

你可能感兴趣的文章
C语言中求字符串的长度
查看>>
localstorage和sessionstorage上手使用记录
查看>>
HDOJ 4974 A simple water problem
查看>>
荣耀手机缅甸仰光店开业,只有我觉得缅甸美女比较多吗?
查看>>
费德勒三盘击败西里奇摘大满贯第19冠
查看>>
融合数据库技术,降低开源MySQL使用成本实践
查看>>
IDC:全球以太网交换机和路由器市场整体看涨
查看>>
暴风集团:冯鑫从未减持个人直接或间接持有上市公司股份
查看>>
今年春运广东水上出行旅客预计将达600万人次
查看>>
国内首座空腹式钢混组合连续桥梁建成通车
查看>>
英国零售商:“无协议脱欧”恐让超市空荡荡
查看>>
拒绝“烂代码”,人人有责
查看>>
2018年中国出生人口下降200万人 专家:不必担忧
查看>>
一汽丰田交响音乐会北京收官 亚洲龙和卡罗拉双擎E+亮相
查看>>
为什么程序员圈内一言不合就开撕的情景很常见?
查看>>
IT骚年——“放荡不羁”,这才是自由该有的样子
查看>>
理解 Istio Service Mesh 中 Envoy 代理 Sidecar 注入及流量劫持
查看>>
致 CODING 用户的元宵问候
查看>>
看Zepto如何实现增删改查DOM
查看>>
《从零构建前后分离的web项目》:前端1.0 终 - 前端性能优化 (多图预警)
查看>>