原因:创建.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请求同时包含数据及其文件的更多相关文章

  1. WebApi 中请求的 JSON 数据字段作为 POST 参数传入

    使用 POST 方式请求 JSON 数据到服务器 WebAPI 接口时需要将 JSON 格式封装成数据模型接收参数.即使参数较少,每个接口仍然需要单独创建模型接收.下面方法实现了将 JSON 参数中的 ...

  2. (转)WebApi发送HTML表单数据:文件上传与多部分MIME

    5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/282 ...

  3. WebApi发送HTML表单数据:文件上传与多部分MIME

    5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/282 ...

  4. Android-Volley网络通信框架(二次封装数据请求和图片请求(包含处理请求队列和图片缓存))

    1.回想 上篇 使用 Volley 的 JsonObjectRequest 和 ImageLoader 写了 电影列表的样例 2.重点 (1)封装Volley 内部 请求 类(请求队列,数据请求,图片 ...

  5. 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 ...

  6. ASP.NET WebApi 学习与实践系列(2)---WebApi 路由请求的理解

    目录 写在前面 WebApi Get 请求 1.无参数的请求 2.一个参数的请求 3.多个参数的请求 4.实体参数的请求 WebApi Post 请求 1.键值对请求 2.dynamic 动态类型请求 ...

  7. Web服务器上可能被包含或被请求的不同脚本源代码文件

    Web服务器上可能被包含或被请求的不同脚本源代码文件的大致数量(建议值为1024~4096). ; 如果你不能确定,则设为 0 :此设定主要用于拥有数千个源文件的站点. apc.optimizatio ...

  8. 微信小程序教学第二章(含视频):小程序中级实战教程之预备篇 - 封装网络请求及 mock 数据

    § 封装网络请求及 mock 数据 本文配套视频地址: https://v.qq.com/x/page/i05544fogcm.html 开始前请把 ch2-3 分支中的 code/ 目录导入微信开发 ...

  9. Response ServletContext 中文乱码 Request 编码 请求行 共享数据 转发重定向

    Day35  Response 1.1.1 ServletContext概念 u 项目的管理者(上下文对象),服务器启动时,会为每一个项目创建一个对应的ServletContext对象. 1.1.2  ...

随机推荐

  1. zookeeper无法启动&quot;Unable to load database on disk&quot;

    自己的虚拟机集群.一次强制关机后,发现slave2的zookeeper起不来了 http://blog.csdn.net/ashic/article/details/47088299 下午5点29:5 ...

  2. Java验证是否为纯数字

    package rbq.codedemo; import java.util.regex.Pattern; /** * Created by rbq on 2016/12/13. */ public ...

  3. 在线生成 QR Code

    http://tool.oschina.net/qr 在线生成二维码(QR码)-采用ZXing与d-project

  4. poj 2689 Prime Distance(大区间筛素数)

    http://poj.org/problem?id=2689 题意:给出一个大区间[L,U],分别求出该区间内连续的相差最小和相差最大的素数对. 由于L<U<=2147483647,直接筛 ...

  5. [Django] Get started with Django -- Install python and virtualenv

    Install python3 on MacOS: brew install python3 Come alone with python3, there are also some other to ...

  6. 面试无忧之Zookeeper总结心得

    为什么需要分布式系统 l 单机系统已经无法满足业务需要 l 高性能硬件价格昂贵 分布式系统带来哪些问题 l 集群中节点数据一致性问题 l 集群产生分区 l 负载问题 l 幂等性问题 l 可用性问题 l ...

  7. Linux硬件信息查询命令

    系统 uname -a              # 查看内核/操作系统/CPU信息 Linux hostname 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 ...

  8. Docker + .NET Core(二)

    原文:Docker + .NET Core(二) 前言: 环境:centos7.5 64 位 正文: 首先我们在宿主机上安装 .NET Core SDK sudo rpm --import https ...

  9. ServletContextListener和ContextLoaderListener的区别

    ServletContext 被 Servlet 程序用来与 Web 容器通信.例如写日志,转发请求.每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享.因为Context可 ...

  10. List&lt;Map&lt;String, String&gt;&gt; 开启 Map&lt;String, List&lt;String&gt;&gt;

    将List变成Map结构体,下面的文字是没有水平! 写作方法传送前土壤很长一段时间.我不知道有没有好的解决办法.我们也希望提供! Map<String, String> map1 = ne ...