服务端接收,并保存图片和文件
仅当 HTTP 请求 Content-Type
值为“multipart/form-data”时,才会填充文件集合。
postman请求URL:http://localhost:49793/api/Pictures/ReceivePictures
[HttpPost]
public HttpResponseMessage ReceivePictures()
{
var httpPostedFiles=HttpContext.Current.Request.File;
if(httpPostedFiles != null)
{
for(int i=0;i < httpPostedFiles.Count;i++)
{
//保存路径
string filePath=@"C:\WebPicture\"+ httpPostedFiles[i].FileName;
httpPostedFiles[i].SaveAs(filePath);
}
string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
Posman测试
服务端接收参数
当 HTTP 请求Content-Type
值为“application/x-www-form-urlencoded”或“multipart/form-data”时,将Form填充该属性
postman请求URL:http://localhost:49793/api/Pictures/ReceiveParameters
[HttpPost]
public HttpResponseMessage ReceiveParameters()
{
NameValueCollection httpPostedParams=HttpContext.Current.Request.Form;
if(httpPostedParams != null)
{
for(int i=0;i < httpPostedParams.Count;i++)
{
//可以采用键值对获取内容,也可以使用数组取值
string strValue=httpPostedParams["123"];
}
string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
服务端接收参数
Content-Type的值不同,接收的数据内容也不同,文件和图片会出现乱码,请选择第一种模式
postman请求URL:http://localhost:49793/api/custormers
[Route("api/Custormers")]
[HttpPost]
public HttpResponseMessage ReceiveParameterCustorm()
{
int iLength=HttpContext.Current.Request.ContentLength;
if(iLength!= 0)
{
byte[] charRec=new byte[iLength];
HttpContext.Current.Request.InputStream.Read(charRec,0,iLength)
string strReceive=System.Text.Encoding.UTF8.GetString(charRec,0,iLength);
//打印到本地
File.WriteAllText(@"c:\WebPicture\log.txt",strReceive);
string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}