嗨,我想使用带有 ASp.net (4.0)、c# 的 box api 2.0 在框中上传文件。我收到 400(错误请求错误)。
以下是我的代码。
`public bool Upload(byte[] FileBytes, string folderId, string FileName) { UploadFileBytes = FileBytes; 上传文件名 = 文件名;
UploadSplitFile(folderId);
return true;
}
public void UploadSplitFile(string FolderId)
{
string Filename = UploadFileName;
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = AssembleFilesBlock();
resultStream.Write(buffer, 0, buffer.Length);
buffer = GetFormattedBoundary(true);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
HttpWebRequest myRequest = CreateRequest(buffer.Length, FolderId);
using (Stream newStream = myRequest.GetRequestStream())
{
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();
}
string response;
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse())
{
using (Stream responseStream = myHttpWebResponse.GetResponseStream())
{
TextReader reader = new StreamReader(responseStream);
response = reader.ReadToEnd();
}
}
}
private byte[] AssembleFile()
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"; parent_id=\"0\"{2}", Guid.NewGuid(), Path.GetFileName(UploadFileName), Environment.NewLine));
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes("Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
buffer = UploadFileBytes;
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private byte[] AssembleFilesBlock()
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleFile();
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private byte[] GetFormattedBoundary(bool isEndBoundary)
{
string template = isEndBoundary ? "--{0}--{1}" : "--{0}{1}";
return Encoding.ASCII.GetBytes(string.Format(template, "AaBbCcX30", Environment.NewLine));
}
private HttpWebRequest CreateRequest(int contentLength, string FolderId)
{
HttpWebRequest webRequest;
webRequest = (HttpWebRequest)WebRequest.Create("https://upload.box.com/api/2.0/files/content");
webRequest.Method = "POST";
webRequest.AllowWriteStreamBuffering = true;
webRequest.ContentType = string.Concat("multipart/form-data;boundary=", "AaBbCcX30");
webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
webRequest.Headers.Add("Accept-Charset", "ISO-8859-1");
webRequest.Headers.Add("Authorization", "Bearer Access Token");
webRequest.ContentLength = contentLength;
return webRequest;
}`