c# WebApi POST请求同时包含数据及其文件
原因:创建.net WebApi的接口API。IIS作为服务端。安卓作为客户端发送json文件及其文件。
Android端使用xUtils3.0实现文件上传
java代码:
//要传递给服务器的json格式参数
JSONObject json = new JSONObject();
try {
json.put("devId", id);
json.put("devName", devName);
json.put("keyWord", keyWord);
} catch (JSONException e) {
e.printStackTrace();
}
//构建RequestParams对象,传入请求的服务器地址URL
RequestParams params = new RequestParams(Constants.UPLOAD_FILE);
params.setAsJsonContent(true);
List<KeyValue> list = new ArrayList<>();
list.add(new KeyValue("file", new File(filePah)));
list.add(new KeyValue("parameters", json.toString()));
MultipartBody body = new MultipartBody(list, "UTF-8");
params.setRequestBody(body);
x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
LogUtil.e("请求结果:" + result);
} @Override
public void onFinished() {
//上传完成
} @Override
public void onCancelled(CancelledException cex) {
//取消上传
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
//上传失败
LogUtil.e("请求失败:" + ex.toString()); }
});
.net WebApi代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Entity;
using Newtonsoft.Json;
using System.Configuration; namespace AndroidWebAPI.Controllers
{
public class AddInfoController : ApiController
{
public IEnumerable<string> PostAddInfo()
{ if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return "请求内容不是表单形式";
}
if (HttpContext.Current.Request.Files.Count >)
{
try
{ var file = HttpContext.Current.Request.Files[];
string fname = DateTime.Now.ToString("yyyyMMddHHmmssfff") + file.FileName; string SavePath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", "File")); if (Directory.Exists(SavePath))
{
Directory.CreateDirectory(SavePath);
}
string fullPathUrl = Path.Combine(SavePath, fname);
file.SaveAs(fullPathUrl);
videoFileName = fname;
}
catch (Exception ex)
{
}
} return PBimLogic.AddProblemListInfo(Plm, videoFileName); } }
}
c# 创建控制台模拟表单上传数据与文件.
创建HttpUpload类
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text; namespace HttpTest
{
public class HttpUpload
{
private ArrayList bytesArray;
private Encoding encoding = Encoding.UTF8;
private string boundary = String.Empty; public HttpUpload()
{
bytesArray = new ArrayList();
string flag = DateTime.Now.Ticks.ToString("x");
boundary = "---------------------------" + flag;
} /// <summary>
/// 合并请求数据
/// </summary>
/// <returns></returns>
private byte[] MergeContent()
{
int length = ;
int readLength = ;
string endBoundary = "--" + boundary + "--\r\n";
byte[] endBoundaryBytes = encoding.GetBytes(endBoundary); bytesArray.Add(endBoundaryBytes); foreach (byte[] b in bytesArray)
{
length += b.Length;
} byte[] bytes = new byte[length]; foreach (byte[] b in bytesArray)
{
b.CopyTo(bytes, readLength);
readLength += b.Length;
} return bytes;
} /// <summary>
/// 上传
/// </summary>
/// <param name="requestUrl">请求url</param>
/// <param name="responseText">响应</param>
/// <returns></returns>
public bool Upload(String requestUrl, out String responseText)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary); byte[] responseBytes;
byte[] bytes = MergeContent(); try
{
responseBytes = webClient.UploadData(requestUrl, bytes);
responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
return true;
}
catch (WebException ex)
{
Stream responseStream = ex.Response.GetResponseStream();
responseBytes = new byte[ex.Response.ContentLength];
responseStream.Read(responseBytes, , responseBytes.Length);
}
responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
return false;
} /// <summary>
/// 设置表单数据字段
/// </summary>
/// <param name="fieldName">字段名</param>
/// <param name="fieldValue">字段值</param>
/// <returns></returns>
public void SetFieldValue(String fieldName, String fieldValue)
{
string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
string httpRowData = String.Format(httpRow, fieldName, fieldValue); bytesArray.Add(encoding.GetBytes(httpRowData));
} /// <summary>
/// 设置表单文件数据
/// </summary>
/// <param name="fieldName">字段名</param>
/// <param name="filename">字段值</param>
/// <param name="contentType">内容内型</param>
/// <param name="fileBytes">文件字节流</param>
/// <returns></returns>
public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
{
string end = "\r\n";
string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string httpRowData = String.Format(httpRow, fieldName, filename, contentType); byte[] headerBytes = encoding.GetBytes(httpRowData);
byte[] endBytes = encoding.GetBytes(end);
byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length]; headerBytes.CopyTo(fileDataBytes, );
fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length); bytesArray.Add(fileDataBytes);
}
}
}
控制台调用:
using System;
using System.IO;
using System.Text; namespace HttpTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!"); try
{
var httpUpload = new HttpUpload();
string txtJsonData= File.ReadAllText(@"D:\Test\HttpTest\HttpTest\HttpTest\JsonData.txt", Encoding.UTF8);
httpUpload.SetFieldValue("parameters", txtJsonData); string path = @"D:\Test\HttpTest\HttpTest\HttpTest\Test.txt";
FileStream fspdf = new FileStream(path, FileMode.Open);
byte[] fileBytepdf = new byte[fspdf.Length];
fspdf.Read(fileBytepdf, , fileBytepdf.Length);
fspdf.Close();
var pdfName = path.Substring(path.LastIndexOf("\\") + );
httpUpload.SetFieldValue(pdfName, pdfName, "application/octet-stream", fileBytepdf);
string responStr = "";
//string _apiUrl = @"http://localhost:51013/api/AddInfo";
string _apiUrl = @"http://192.168.2.1:10000//api/AddInfo";
bool suc = httpUpload.Upload(_apiUrl, out responStr);
}
catch (Exception ex)
{ throw ex;
} Console.ReadLine();
}
}
}
c# WebApi POST请求同时包含数据及其文件的更多相关文章
- WebApi 中请求的 JSON 数据字段作为 POST 参数传入
使用 POST 方式请求 JSON 数据到服务器 WebAPI 接口时需要将 JSON 格式封装成数据模型接收参数.即使参数较少,每个接口仍然需要单独创建模型接收.下面方法实现了将 JSON 参数中的 ...
- (转)WebApi发送HTML表单数据:文件上传与多部分MIME
5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/282 ...
- WebApi发送HTML表单数据:文件上传与多部分MIME
5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/282 ...
- Android-Volley网络通信框架(二次封装数据请求和图片请求(包含处理请求队列和图片缓存))
1.回想 上篇 使用 Volley 的 JsonObjectRequest 和 ImageLoader 写了 电影列表的样例 2.重点 (1)封装Volley 内部 请求 类(请求队列,数据请求,图片 ...
- C# -- HttpWebRequest 和 HttpWebResponse 的使用 C#编写扫雷游戏 使用IIS调试ASP.NET网站程序 WCF入门教程 ASP.Net Core开发(踩坑)指南 ASP.Net Core Razor+AdminLTE 小试牛刀 webservice创建、部署和调用 .net接收post请求并把数据转为字典格式
C# -- HttpWebRequest 和 HttpWebResponse 的使用 C# -- HttpWebRequest 和 HttpWebResponse 的使用 结合使用HttpWebReq ...
- ASP.NET WebApi 学习与实践系列(2)---WebApi 路由请求的理解
目录 写在前面 WebApi Get 请求 1.无参数的请求 2.一个参数的请求 3.多个参数的请求 4.实体参数的请求 WebApi Post 请求 1.键值对请求 2.dynamic 动态类型请求 ...
- Web服务器上可能被包含或被请求的不同脚本源代码文件
Web服务器上可能被包含或被请求的不同脚本源代码文件的大致数量(建议值为1024~4096). ; 如果你不能确定,则设为 0 :此设定主要用于拥有数千个源文件的站点. apc.optimizatio ...
- 微信小程序教学第二章(含视频):小程序中级实战教程之预备篇 - 封装网络请求及 mock 数据
§ 封装网络请求及 mock 数据 本文配套视频地址: https://v.qq.com/x/page/i05544fogcm.html 开始前请把 ch2-3 分支中的 code/ 目录导入微信开发 ...
- Response ServletContext 中文乱码 Request 编码 请求行 共享数据 转发重定向
Day35 Response 1.1.1 ServletContext概念 u 项目的管理者(上下文对象),服务器启动时,会为每一个项目创建一个对应的ServletContext对象. 1.1.2 ...
随机推荐
- [Docker] Build Your Own Custom Docker Image
In this lesson we will cover how to build your own custom Docker image from scratch. We'll walk thro ...
- MySQL参数文件位置
对于linux/unix: mysql --help|grep my.cnf /etc/my.cnf, /etc/mysql/my.cnf, /usr/local/etc/my.cnf, ~/.m ...
- 《高性能MySQL》--复制笔记
复制解决的问题 1,数据分布 MySQL复制通常不会对带宽造成很大的压力,但在5.1版本引入的基于行的复制会比传统的基于语句的复制模式的带宽压力更大.你可以随意地停止或开始复制,并在不同的地理位置来分 ...
- TensorFlow中卷积
CNN中的卷积核及TensorFlow中卷积的各种实现 声明: 1. 我和每一个应该看这篇博文的人一样,都是初学者,都是小菜鸟,我发布博文只是希望加深学习印象并与大家讨论. 2. 我不确定的地方用了“ ...
- 前端切图:一个好看的表格css样式
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> ...
- eclipse配置本地服务
1.下载安装eclipse 2.下载tomcat文件,并解压 3.下载tomcat插件 com.sysdeo.eclipse.tomcat_3.3.0 将com.sysdeo.eclipse.tomc ...
- clipboard.js小说明
github主页 clipboard.js是一个github上的开源项目,可以实现纯 JavaScript (无 Flash)的浏览器内容复制到系统剪贴板的功能. 用法 <script type ...
- Net锁
Net分布式锁的实现 序言 我晚上有在公司多呆会儿的习惯,所以很多晚上我都是最后一个离开公司的.当然也有一些同事,跟我一样喜欢在公司多搞会儿.这篇文章就要从,去年年末一个多搞会的晚上说起,那是一个夜黑 ...
- Linux input
Linux input 输入设备都有共性:中断驱动+字符IO,基于分层的思想,Linux内核将这些设备的公有的部分提取出来,基于cdev提供接口,设计了输入子系统,所有使用输入子系统构建的设备都使用主 ...
- Android显示gif格式图片
大家知道,在Android中使用ImageView来显示gif格式的图片,我们无法得到gif格式图片该有的效果,它只会停在第一帧上,而不会继续.这时只能看到一张静态的图片,这里我们可以使用个简单的方法 ...