当通过REST上传文件到OneDrive时,得到一个400 Bad Request错误
本文关键字:一个 错误 Request Bad REST OneDrive 文件 | 更新日期: 2023-09-27 17:51:18
我试图使用REST将文件上传到OneDrive,但当我尝试这样做时,我看到了400个坏请求错误。这是我的代码:
//Where I call it
//fileLoc being C:''path''test.doc
HttpUploadFile("https://apis.live.net/v5.0/folder.xxxxxxxx/files/" + "?" + access_token, @fileLoc, "file", "application/octet-stream");
public static void HttpUploadFile(string url, string file, string paramName, string contentType)
{
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "A300x";// "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("'r'n--" + boundary + "'r'n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name='"{0}'"; filename='"{1}'"'r'nContent-Type: {2}'r'n'r'n";
string header = string.Format(headerTemplate, paramName, "TEMPTEST.docx", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("'r'n--" + boundary + "--'r'n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
MessageBox.Show("Success!");
}
catch (Exception ex)
{
log.Error("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
MessageBox.Show("There was an error!" + Environment.NewLine + ex.Message);
}
finally
{
wr = null;
}
}
有谁知道我的问题是什么吗?我最初没有将我的范围设置为能够写作,但已经纠正了这一点,因此这不是问题。
我猜内容处理头是错误的。规范说标题应该看起来像
Content-Disposition: Attachment; filename=example.html