c# - 使用 C# 中的 post 请求上传到 box.net

标签 c# asp.net httpwebrequest box-api

我想通过 api 在 box.net 上上传文件,我正在以这种方式通过发布请求发布我的文件

根据 Box.NET 的文档,这里是请求 url

https://upload.box.net/api/1.0/upload/<auth token>/<folder id>

这是文档 http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download

WebRequest request = WebRequest.Create("https://upload.box.net/api/1.0/upload...;
request.Method = "POST";

byte[] byteArray = File.ReadAllBytes(@"C:\a.docx");

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close(); 

我收到这条消息“upload_no_files_found”的异常

最佳答案

根据 this page 在示例上传请求中,Box.net 请求一些参数,如 new_file1shareemails[]

因此您需要发送此参数而不仅仅是文件。来自 MSDN sample for how to post parametres关键是用您要发送的文件制作这个完整的字符串。我重点关注这一行,它是要发送的文件的参数。

    string postData = "firstone=" + inputData;
    ASCIIEncoding encoding = new ASCIIEncoding ();
    byte[] byte1 = encoding.GetBytes (postData);

对于你的情况,这看起来像

    string postData = "share=1&emails[]=test@domain.com&new_file1=" + FileData;
    ASCIIEncoding encoding = new ASCIIEncoding ();
    byte[] byte1 = encoding.GetBytes (postData);

你的最终代码必须是这样的:

     WebRequest request = WebRequest.Create("https://upload.box.net/api/1.0/<auth_token>/<file_id>/<version_id>;
     request.Method = "POST";

    // open and read file
    byte[] byteArray = File.ReadAllBytes(@"C:\a.docx");

    // make the parametres
    string postData = "share=1&emails[]=test@domain.com&new_file1=";
    ASCIIEncoding encoding = new ASCIIEncoding ();
    byte[] parametres = encoding.GetBytes (postData);

    // set the Type
    request.ContentType = "application/x-www-form-urlencoded";
    // the full length.
    request.ContentLength = parametres.Length + byteArray.Length;

    // now we go for post
    Stream dataStream = request.GetRequestStream();
    // send the parametres
    dataStream.Write(parametres, 0, parametres.Length);
    // follow the file
    dataStream.Write(byteArray, 0, byteArray.Length);

    // flush and close what you have send  
    dataStream.Close();

现在这是想法,但我无法调试此代码,也无法对其进行测试,也许它从一开始就无法正常工作,需要进行一些更改和调试。

关于c# - 使用 C# 中的 post 请求上传到 box.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11292092/

相关文章:

c# - asp.net 中的配置设置

.net - 如何通过代理发送 WebRequest?

c# - azure 从服务总线队列中删除预定消息

c# - 匹配未由 & 和 ; 包围的文本

c# - 在 Repository/UnitOrWork 之上使用服务类时,我应该将逻辑不适合 Repository 的常用数据访问代码放在哪里?

c# - 如何在 SelectCommand Asp.net 中设置传递变量

html - 列表框 CSS 标记不起作用,div 不并排显示

css - 性能,一次性提供所有CSS,还是根据需要提供?

c# - 如何在 C# 中处理中断的 HTTP 连接

c# - SecurityAttribute.Unrestricted 问题