ReOSS上传文件400错误,提示MalformedPOSTRequest
Unity3D模仿WWW实现的兼容OSS的Multipart上传类
public class MultiPartUpload
{
public bool isDone;
public bool isSuccess;
public string rspString;
private HttpWebRequest request;
private HttpWebResponse response;
private Stream streamResponse;
private string mUrl;
private Dictionary<string, string> mKeyValues;
private string mFileName;
private byte[] mFileData;
private byte[] mPostData;
private string mBoundary;
private IAsyncResult mResult;
public MultiPartUpload(string url, Dictionary<string, string> keyValues, string filename, byte[] data)
{
streamResponse = null;
isDone = false;
isSuccess = false;
rspString = "";
mUrl = url;
mKeyValues = keyValues;
mFileName = filename;
mFileData = data;
mBoundary = "--------9431149156168";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Timeout = -1;
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + mBoundary;
this.request = webRequest;
mResult = webRequest.BeginGetRequestStream(getRequestStreamCallback, this);
}
private void getRequestStreamCallback(IAsyncResult ar)
{
try
{
Stream postStream = request.EndGetRequestStream(ar);
string boundary = mBoundary;
string requestBody = "--" + boundary + "\r\n";
foreach(KeyValuePair<string, string> keyValue in mKeyValues)
{
string postField = "Content-Disposition: form-data; name=\"" + keyValue.Key + "\"\r\n"
+ "\r\n" + keyValue.Value + "\r\n"
+ "--" + boundary + "\r\n";
requestBody += postField;
}
string tail = "\r\n" + "--" + boundary + "--\r\n";
List<byte> postData = new List<byte>();
{
postData.AddRange(System.Text.Encoding.Default.GetBytes(requestBody));
string fileString = "Content-Disposition: form-data; name=\"file\"; filename=\"" + mFileName + "\"\r\n\r\n";
postData.AddRange(System.Text.Encoding.Default.GetBytes(fileString));
postData.AddRange(mFileData);
postData.AddRange(System.Text.Encoding.Default.GetBytes(tail));
}
mPostData = postData.ToArray();
postStream.Write(mPostData, 0, mPostData.Length);
postStream.Close();
mResult = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(getResponseCallback), this);
}
catch (Exception e)
{
rspString = e.Message;
isDone = true;
}
}
private void getResponseCallback(IAsyncResult ar)
{
try
{
HttpWebResponse rsp = (HttpWebResponse)request.EndGetResponse(ar);
Stream streamRsp = rsp.GetResponseStream();
StreamReader streamRead = new StreamReader(streamRsp);
rspString = streamRead.ReadToEnd();
isSuccess = rsp.StatusCode == HttpStatusCode.OK;
isDone = true;
streamRsp.Close();
streamRead.Close();
rsp.Close();
}
catch (Exception e)
{
rspString = e.Message;
isDone = true;
}
}
}