1

我正在尝试使用 box api 在框中上传文件

它的给我错误是错误的请求

这段代码有什么问题请帮助我

public static FileDetails PutFile(string token, byte[] filebytes, string FolderId, string filename, string filecontentType) {

    Encoding encoding = Encoding.UTF8;
    FileDetails objFile = new FileDetails();
    Stream formDataStream = new System.IO.MemoryStream();
    string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
    string boundry = formDataBoundary;
    string contentType = "multipart/form-data;boundary=" + boundry;

    try
    {

        //request.ContentLength = bytes.Length;

        Attributes attributes = new Attributes();
        attributes.name = Path.GetFileNameWithoutExtension(filename);
        attributes.parent = new Parent();
        attributes.parent.id = FolderId;

        string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                boundry,
                "file",
                filename,
                filecontentType ?? "application/octet-stream");

        formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

        formDataStream.Write(filebytes, 0, filebytes.Length);

        string jsonstring = new JavaScriptSerializer().Serialize(attributes);
        string data = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\";\r\n{2}\r\n\r\n",
                boundry,
                "attributes",
                jsonstring);

        formDataStream.Write(encoding.GetBytes(data), 0, encoding.GetByteCount(data));

        string footer = "\r\n--" + boundry + "--\r\n";

        formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));



        formDataStream.Position = 0;
        byte[] formData = new byte[formDataStream.Length];
        formDataStream.Read(formData, 0, formData.Length);
        formDataStream.Close();

        var uri = "https://upload.box.com/api/2.0/files/content";

        var request = (HttpWebRequest)WebRequest.Create(uri.ToString());
        request.Method = "POST";
        request.ContentType = contentType;
        request.Headers.Add("Authorization", "Bearer " + token);
        request.ContentLength = formData.Length;


        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(formData, 0, formData.Length);
            requestStream.Close();
        }


        var response = request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());
        var accessToken = reader.ReadToEnd();

        response.Close();


    }
    catch (WebException e)
    {
        var resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
    }

    return objFile;
}
4

0 回答 0