Community
I'm trying to attach a new file to FLC using RestSharp and am having issues getting the request formatted correctly.
There didn't seem to be any posts that gave any good, complete, examples of how to use RestSharp to attach a new file so hopefully we can answer it here.
This is assuming the file is new to FLC.
Here is my code so far:
public File AddFile(long workspaceId, long itemId, string filePath) { string resource = string.Format("/api/rest/v1/workspaces/{0}/items/{1}/attachments", workspaceId, itemId); RestRequest request = new RestRequest(resource, Method.POST); request.RequestFormat = DataFormat.Json; request.AddHeader("Content-Type", "multipart/mixed"); request.AddHeader("Accept", "application/json"); //add cookies which contains the login information AddCookies(request); if (System.IO.File.Exists(filePath)) { FileStream fs = new FileStream(filePath, FileMode.Open); BinaryReader br = new BinaryReader(fs); FileInfo fi = new FileInfo(filePath); byte[] fileBytes = br.ReadBytes((int)fi.Length); string filevalue = System.Convert.ToBase64String(fileBytes); request.AddHeader("Content-Type", "application/json"); request.AddParameter("fileName", fi.Name); request.AddParameter("resourceName", fi.Name); request.AddParameter("description", "TEST");
request.AddHeader("Content-Type", "application/octet-stream");
string content = string.Format("*; filename={0};", fi.Name);
request.AddHeader("Content-Disposition", content);
request.AddBody(fileBytes);
//request.AddFile("filename", fileBytes, fi.Name, "application/octet-stream");
//request.AddFile("filename", fi.FullName);
//request.AddFile("filename", fs.CopyTo, fi.Name); IRestResponse response = m_client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.NoContent) { SimpleJson.CurrentJsonSerializerStrategy = SimpleJson.DataContractJsonSerializerStrategy; Attachment result = SimpleJson.DeserializeObject<Attachment>(response.Content); return result.File; } else { return null; } } else { //File did not exist return null; } } private void AddCookies(RestRequest request) { foreach (var cookie in Cookies) { request.AddCookie(cookie.Key, cookie.Value); } }
As you can see I've tried a few methods of getting the Multi-Part request formatted correctly but all I get are 500 and 400 errors in the response...
Hi,
this line
string content = string.Format("*; filename={0};", fi.Name)
should have a size element
string content = string.Format("*; filename={0}; size=-1", fi.Name);
-1 should work for testing but you should send actual byte size of the attachment
Hope this helps.