
WCF收到的数据也包括了MIME头。所以WCF收到的长度大于啊Android发送的长度,因为MIME头信息还是有规律的,就是最后"Content-Transfer-Encoding: binary\r\n\r\n",所以解析数据的时候,从这些字符后开始。
C# code?12345678910111213141516171819202122232425 internal static byte[] GetBytesFromStream(Stream stream, System.Text.Encoding encoding) { // Read the stream into a byte array byte[] data = ToByteArray(stream)List<byte>dataList = new List<byte>() // Copy to a string for header parsing string content = encoding.GetString(data) string matchValue = "Content-Transfer-Encoding: binary\r\n\r\n"int lastIndex = content.LastIndexOf(matchValue) int startingIndex = lastIndex + matchValue.Length byte[] bytes = encoding.GetBytes(content.Substring(0, startingIndex - 1))int bytesLength = bytes.Length for (int i = bytesLength + 1i <data.Lengthi++) { dataList.Add(data[i])} return dataList.ToArray()}
还有一种是使用MultipartParser
参考:
Reading file input from a multipart/form-data POST
C# code?12345678910 public void Upload(Stream stream) { MultipartParser parser = new MultipartParser(stream)if (parser.Success) { // Save the file SaveFile(parser.Filename, parser.ContentType, parser.FileContents)} }
使用 WCF 实现 RESTful 方式的 WebService
后台的代码都是这样写的MultipartEntity entity = new MultipartEntity()
entity.addPart("param1", new StringBody("中国", Charset.forName("UTF-8")))
entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")))
entity.addPart("param3", new FileBody(new File("C:\\1.txt")))
HttpPost request = new HttpPost(“http://localhost/index.html”)
request.setEntity(entity)
在这里HTTPclient 的作用是在 jsp 中模拟一个浏览器,即 HTTP 协议的客户端(client)
你的后台代码是将你本地服务器上的文件像浏览器那样上传到目标服务器
C:\\1.txt 是你本地服务器中的文件,当然文件名是你自己定的
至于 multipart/form-data 声明,那是由 HttpPost 的参数 MultipartEntity 自动加上的
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)