尝试将文件上传到服务器的multipart / form-data

时间:2014-05-12 14:06:46

标签: request httprequest multipartform-data webrequest

我正在开发一个客户端,使用multipart / form-data将图像发送到服务器, 我的搭档是使用mac而我是win8。

我按照Mac上的方式发送所有内容,但是从客户端来说,它无法通过网络服务,错误信息是:"内容正文错误"

这是我的代码:

string boundary = "96c334567890";
byte[] sub = AuxiliaryMethods.ReadFileInCloudStorage(urlImg, i);

//POST 
// Create a request using a URL that can receive a post. 
WebRequest request = (HttpWebRequest)WebRequest.Create(urlImgPost);

// Create POST data and convert it to a byte array.
string strAux = "--" + boundary + "\r\n" + 
"Content-Disposition: form-data; name=\"file\"; filename=\"photo" + i + ".jpg\"" + "\r\n" +
"Content-Type: image/jpeg" + "\r\n\r\n" +
System.Text.Encoding.UTF8.GetString(sub) + "\r\n" +
boundary + "--";
byte[] byteArray = Encoding.UTF8.GetBytes(strAux);

// Set the Method property of the request to POST.
request.Method = "POST";
request.Headers.Add("Authorization: Token token=token");
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data; boundary="+boundary;

我的标题和正文看起来应该是这样的:

POST https://apidev.test.pt/images HTTP/1.1
Authorization: Token token=token
Content-Type: multipart/form-data; boundary=96c334567890
Host: apidev.test.pt
Content-Length: 764939

--96c334567890
content-disposition: form-data; name="file"; filename="photo1.jpg"
content-type: image/jpeg

(image binary data)

96c334567890--

我应该添加一些东西,因为我是在Windows系统上还是我的请求是以错误的方式完成的? 这是使用RFC2388

格式化的

1 个答案:

答案 0 :(得分:0)

将文件上传到服务器

strBoundary = AlphaNumString(32)

strBody = "--" & strBoundary & vbCrLf

strBody = strBody & "Content-Disposition: form-data; name=""" & UploadName & """; filename=""" & filename & """" & vbCrLf
strBody = strBody & "Content-Type: " & MimeType & vbCrLf
strBody = strBody & vbCrLf & strData
strBody = strBody & vbCrLf & "--" & strBoundary & "--"


Length = Len(strBody)

strHTTP = "POST " & DestUrl.URI & "?" & DestUrl.Query & " HTTP/1.0" & vbCrLf
strHTTP = strHTTP & "Host: " & DestUrl.Host & vbCrLf
strHTTP = strHTTP & "Content-Type: multipart/form-data, boundary=" & strBoundary & vbCrLf
strHTTP = strHTTP & "Content-Length: " & Length & vbCrLf & vbCrLf
strHTTP = strHTTP & strBody