Загрузить файл в поле api с multipart/form-data в C#

Я пытаюсь загрузить файл в поле, используя окно API

"Дай мне ошибку - плохой запрос"

что не так в этом коде, пожалуйста, помогите мне

public static FileDetails PutFile (строковый токен, byte[] filebytes, строковый FolderId, строковое имя файла, строковый 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;
}

0 ответов

Другие вопросы по тегам