如何设置的WebAPItplinkac控制器设置的multipart / form-data的

拒绝访问 | www. | 百度云加速
请打开cookies.
此网站 (www.) 的管理员禁止了您的访问。原因是您的访问包含了非浏览器特征(3bf31c1ec626437c-ua98).
重新安装浏览器,或使用别的浏览器输入关键字或相关内容进行搜索
最近研究了下webapi服务器下图片的上传功能,屁话不多说,直接看代码吧 public Task&HttpResponseMessage& PostFormData()
// Check if the request contains multipart/form-data.
// 检查该请求是否含有multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
string root = HttpContext.Current.Server.MapPath(&~/userImage&);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
// 读取表单数据,并返回一个async任务
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith&HttpResponseMessage&(t =&
if (t.IsFaulted || t.IsCanceled)
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
// This illustrates how to get the file names.
// 以下描述了如何获取文件名
foreach (MultipartFileData file in provider.FileData)
//新文件夹路径
string newRoot = root + &\\& + provider.FormData.GetValues(1)[0].ToString();
if (!Directory.Exists(newRoot))
Directory.CreateDirectory(newRoot);
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine(&Server file path: & + file.LocalFileName);
if (File.Exists(file.LocalFileName))
//原文件名称
string fileName = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2);
//新文件名称
string newFileName = provider.FormData.GetValues(0)[0] + &.& + fileName.Split(new char[] { '.' })[1];
File.Move(file.LocalFileName, newRoot + &\\& + newFileName);
return Request.CreateResponse(HttpStatusCode.OK);
\n这个也是在网上找的资料,在此基础上添加了修改文件名功能,图片会保存在userimage文件夹下的子目录(如没有userimage就手动创建个),子目录的名称为客户端task.addData(&&,&&)添加的内容,文件名为客户端生成的随机数.
这样写有个bug,上传多张图片时,共用一个随机数导致文件已存在出错,所以随机数那块改成系统时间+随机数吧
要回复文章请先或其他回答(5)
HttpContext.Request.Form["name"]
byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length]; HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length); string req = System.Text.Encoding.Default.GetString(byts);
这是直接获取post上来的字符流数据。什么编码送的什么编码收就没有问题了。如果是你发送的表单就Request.Form去收。记住字符流数据只能收一次哟。
没发现一个回答正确的
正确答案如下
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.R//定义传统request对象
string name = request.Form["name"];
好多凭空想象的回答
HttpRequest rq=
HttpContext.Current.R
&&&您需要以后才能回答,未注册用户请先。(转)WebApi发送HTML表单数据:文件上传与多部分MIME - 贫民窟里的程序高手 - 博客园
5.3 Sending HTML Form Data5.3 发送HTML表单数据(2)
本文引自:/r01cn/archive//2826230.html
By Mike Wasson|June 21, 2012作者:Mike Wasson | 日期:
Part 2: File Upload and Multipart MIME第2部分:文件上传与多部分MIME
This tutorial shows how to upload files to a web API. It also describes how to process multipart MIME data.本教程演示如何对Web API上传文件。也描述如何处理多部分MIME数据。
Here is an example of an HTML form for uploading a file:以下是一个上传文件的HTML表单(如图5-8):
&form name="form1" method="post" enctype="multipart/form-data" action="api/upload"&
&label for="caption"&Image Caption&/label&
&input name="caption" type="text" /&
&label for="image1"&Image File&/label&
&input name="image1" type="file" /&
&input type="submit" value="Submit" /&
图5-8. 文件上传表单
This form contains a text input control and a file input control. When a form contains a file input control, the&enctype&attribute should always be "multipart/form-data", which specifies that the form will be sent as a multipart MIME message.该表单有一个文本输入控件和一个文件输入控件。当表单含有文件输入控件时,其enctype标签属性应当总是&multipart/form-data&,它指示此表单将作为多部分MIME消息进行发送。
The format of a multipart MIME message is easiest to understand by looking at an example request:通过考察一个示例请求,很容易理解multipart(多部分)MIME消息的格式:
POST http://localhost:50460/api/values/1 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/ Firefox/12.0
Accept: text/html,application/xhtml+xml,application/q=0.9,*/*;q=0.8
Accept-Language: en-us,q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form- boundary=---------------------------
Content-Length: 29278
-----------------------------
Content-Disposition: form- name="caption"
Summer vacation
-----------------------------
Content-Disposition: form- name="image1"; filename="GrandCanyon.jpg"
Content-Type: image/jpeg
(Binary data not shown)(二进制数据,未列出)
-------------------------------
This message is divided into two&parts, one for each form control. Part boundaries are indicated by the lines that start with dashes.这条消息分成两个部件(parts),分别用于每个表单控件。部件边界由以一些破折号开始的行指示。
The part boundary includes a random component ("") to ensure that the boundary string does not accidentally appear inside a message part.部件边界包含了一个随机组件(&&),以确保边界字符串不会偶然出现在消息部件之中。
Each message part contains one or more headers, followed by the part contents.每一个消息部件含有一个或多个报头,后跟部件内容。
The Content-Disposition header includes the name of the control. For files, it also contains the file name.Content-Disposition(内容布置)报头包括控件名称。对于文件,它也包括文件名。
The Content-Type header describes the data in the part. If this header is omitted, the default is text/plain.Content-Type(内容类型)报头描述部件中的数据。如果该报头被忽略,默认为text/plain(文本格式)。
In the previous example, the user uploaded a file named GrandCanyon.jpg, with content type image/ and the value of the text input was "Summer Vacation".在上一示例中,用户上传名为GrandCanyon.jpg的文件,其内容类型为image/jpeg,而文本输入框的值为&Summer Vacation&。
File Upload文件上传
Now let's look at a Web API controller that reads files from a multipart MIME message. The controller will read the files asynchronously. Web API supports asynchronous actions using the&. First, here is the code if you are targeting .NET Framework 4.5, which supports the&async&and&await&keywords.现在,让我们考查从一个多部分MIME消息读取文件的控制器。该控制器将异步读取文件。Web API支持使用&(这是关于.NET并行编程的MSDN文档 & 译者注)&的异步动作。首先,以下是针对.NET Framework 4.5的代码,它支持async和await关键字。
using System.D
using System.N
using System.Net.H
using System.Threading.T
using System.W
using System.Web.H
public class UploadController : ApiController
public async Task&HttpResponseMessage& PostFormData()
// Check if the request contains multipart/form-data.
// 检查该请求是否含有multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// 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(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
return Request.CreateResponse(HttpStatusCode.OK);
catch (System.Exception e)
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
Notice that the controller action does not take any parameters. That's because we process the request body inside the action, without invoking a media-type formatter.注意,控制器动作不取任何参数。这是因为我们是在动作中处理请求体的,不必调用media-type格式化器。
The&IsMultipartContent&method checks whether the request contains a multipart MIME message. If not, the controller returns HTTP status code 415 (Unsupported Media Type).IsMultipartContent方法检查该请求是否含有多部分MIME消息。如果不是,控制器返回HTTP状态码415(不支持的媒体类型)。
The&MultipartFormDataStreamProvider&class is a helper object that allocates file streams for uploaded files. To read the multipart MIME message, call the&ReadAsMultipartAsync&method. This method extracts all of the message parts and writes them into the streams provided by the&MultipartFormDataStreamProvider.MultipartFormDataStreamProvider类是一个辅助器对象,它为上传文件分配文件流。为了读取多部分MIME消息,需调用ReadAsMultipartAsync方法。该方法提取所有消息部件,并把它们写入由MultipartFormDataStreamProvider提供的流中。
When the method completes, you can get information about the files from the&FileData&property, which is a collection of&MultipartFileDataobjects.当该方法完成时,你可以通过FileData属性获得文件的信息,该属性是一个MultipartFileData对象的集合。
MultipartFileData.FileName&is the local file name on the server, where the file was saved.MultipartFileData.FileName是保存此文件的服务器上的一个本地文件名。
MultipartFileData.Headers&contains the part header (not the request header). You can use this to access the Content_Disposition and Content-Type headers.MultipartFileData.Headers含有部件报头(不是请求报头)。你可以用它来访问Content_Disposition和Content-Type报头。
As the name suggests,&ReadAsMultipartAsync&is an asynchronous method. To perform work after the method completes, use a&&(.NET 4.0) or the&await&keyword (.NET 4.5).正如名称所暗示的那样,ReadAsMultipartAsync是一个异步方法。为了在该方法完成之后执行一些工作,需要使用&&(.NET 4.0)或await关键字(.NET 4.5)。
Here is the .NET Framework 4.0 version of the previous code:以下是前述代码的.NET Framework 4.0版本:
public Task&HttpResponseMessage& PostFormData()
// Check if the request contains multipart/form-data.
// 检查该请求是否含有multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
// 读取表单数据,并返回一个async任务
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith&HttpResponseMessage&(t =&
if (t.IsFaulted || t.IsCanceled)
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
// 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);
Reading Form Control Data读取表单控件数据
The HTML form that I showed earlier had a text input control.前面显示的HTML表单有一个文本输入控件。
&label for="caption"&Image Caption&/label&
&input name="caption" type="text" /&
You can get the value of the control from the&FormData&property of the&MultipartFormDataStreamProvider.&可以通过MultipartFormDataStreamProvider的FormData属性获取控件的值。
public async Task&HttpResponseMessage& PostFormData()
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
// Show all the key-value pairs.
// 显示所有&键-值&对
foreach (var key in provider.FormData.AllKeys)
foreach (var val in provider.FormData.GetValues(key))
Trace.WriteLine(string.Format("{0}: {1}", key, val));
return Request.CreateResponse(HttpStatusCode.OK);
catch (System.Exception e)
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
FormData&is a&NameValueCollection&that contains name/value pairs for the form controls. The collection can contain duplicate keys. Consider this form:FormData是一个NameValueCollection(名字/值集合),它含有表单控件的&名字/值&对。该集合可能含有重复键。考虑以下表单(如图5-9):
&form name="trip_search" method="post" enctype="multipart/form-data" action="api/upload"&
&input type="radio" name="trip" value="round-trip"/&
Round-Trip
&input type="radio" name="trip" value="one-way"/&
&input type="checkbox" name="options" value="nonstop" /&
Only show non-stop flights
&input type="checkbox" name="options" value="airports" /&
Compare nearby airports
&input type="checkbox" name="options" value="dates" /&
My travel dates are flexible
&label for="seat"&Seating Preference&/label&
&select name="seat"&
&option value="aisle"&Aisle&/option&
&option value="window"&Window&/option&
&option value="center"&Center&/option&
&option value="none"&No Preference&/option&
图5-9. 有重复键的表单
The request body might look like this:该请求体看上去可能像这样:
-----------------------------7dc1d
Content-Disposition: form- name="trip"
round-trip
-----------------------------7dc1d
Content-Disposition: form- name="options"
-----------------------------7dc1d
Content-Disposition: form- name="options"
-----------------------------7dc1d
Content-Disposition: form- name="seat"
-----------------------------7dc1d--
In that case, the FormData collection would contain the following key/value pairs:在这种情况下,FormData集合会含有以下&键/值&对:
trip: round-trip
options: nonstop
options: dates
seat: window}

我要回帖

更多关于 pcsx2控制器设置 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信