Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to upload file in box using box api

its Give me Error is Bad Request

whats wrong in this code please help me

public static FileDetails PutFile(string token, byte[] filebytes, string FolderId, string filename, string
C#

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;
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900