3

I am trying to upload an image using Zendesk API v2, I am posting the file to /api/v2/uploads.json using RestSharp, and the file appears in the ticket once I create the ticket and add the attachment, the issue is that if I upload an image it won't open on the ticket, it is broken, if its a .txt file it has extra data there, this is my method:

var client = new RestSharp.RestClient(model.RequestUri);
client.Authenticator = new HttpBasicAuthenticator(string.Format("{0}/token", model.Username), model.Password);

var request = new RestRequest("/api/v2/uploads.json", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "text/plain");
request.AlwaysMultipartFormData = true;
request.Parameters.Clear();

request.RequestFormat = RestSharp.DataFormat.Json;
//request.AddBody(createUpload);
byte[] bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Media/uploads/test.txt"));
request.AddFileBytes("Attachment", bytes, "test.txt", contentType: "text/plain");
request.AddParameter("filename", "test.txt");

IRestResponse response = client.Execute(request);
var content = JObject.Parse(response.Content);
return content["upload"]["token"].ToString();

This is the resulting txt file that's attached to the ticket:

-------------------------------28947758029299
Content-Disposition: form-data; name="filename"

test.txt
-------------------------------28947758029299
Content-Disposition: form-data; name="Attachment"; filename="test.txt"
Content-Type: application/octet-stream

testing txt
-------------------------------28947758029299--

The original file just has:

testing txt

Any ideas of what the error could be?

Thanks.

Dawid Rutkowski
  • 2,658
  • 1
  • 29
  • 36
LeoTorres
  • 142
  • 1
  • 10
  • Hello @LeoTorres , I am having the same problem. Did you get the fix for it. Any solution without using the JustEat API – Anuj Sharma Dec 04 '17 at 06:46

5 Answers5

2

I solved the issue using an external library called ZendeskApi that's recommended in the Zendesk documentation: https://github.com/justeat/ZendeskApiClient

By using this library I was able to upload the attachments successfully and it works with any kind of file as well. It is also very easy to use, my method looks like this now:

IZendeskClient client = new ZendeskClient(
    new Uri(model.RequestUri),
    new ZendeskDefaultConfiguration(model.Username,
            model.Password)
);

UploadRequest request = new UploadRequest() {
    Item = model.Attachment.ConvertToZendeskFile()
};

IResponse<Upload> response = client.Upload.Post(request);
return response.Item.Token;

This is the ConvertToZendeskFile method:

private static ZendeskFile ConvertToZendeskFile(this HttpPostedFileBase rawFile)
{
    return new ZendeskFile()
    {
        FileName = rawFile.FileName,
        ContentType = rawFile.ContentType,
        InputStream = rawFile.InputStream
    };
}

The last step was creating a class that implemented IHttpPostedFile from the API:

public class ZendeskFile : IHttpPostedFile
{
    public string ContentType { get; set; }
    public string FileName { get; set; }
    public Stream InputStream { get; set; }
}

This solved the issue for me, I hope it can help anyone facing the same problem.

LeoTorres
  • 142
  • 1
  • 10
  • thanks your answer did help, i just used the client to see what request is getting created and replicated it in http web request. – coder771 Oct 01 '18 at 14:37
1

Need to add header ContentType=application/binary and provide file name in the URI ?filename=myfile.dat:

HttpClient client = [...];
var content = new ByteArrayContent(fileByteArray);
content.Headers.ContentType = new MediaTypeHeaderValue("application/binary");
HttpResponseMessage response = await client.PostAsync(url, content);
string responseString = await response.Content.ReadAsStringAsync();

From Zendesk documentation:

curl "https://{subdomain}.zendesk.com/api/v2/uploads.json?filename=myfile.dat&token={optional_token}" \
-v -u {email_address}:{password} \
-H "Content-Type: application/binary" \
--data-binary @file.dat -X POST
Hp93
  • 1,349
  • 3
  • 14
  • 23
0

I've managed to upload images and PDFs to Zendesk using a code snippet similar to this:

var client = new RestClient(apiUrl);
client.Authenticator = new HttpBasicAuthenticator(username + "/token", token);
client.AddDefaultHeader("Accept", "application/json");

string name = "name";
byte[] data; //Read all bytes of file
string filename = "filename.jpg";

var request = new RestRequest("/uploads.json", Method.POST);
request.AddFile(name, data, filename, "application/binary");
request.AddQueryParameter("filename", filename);
var response = client.Execute(request);
Thomas D
  • 89
  • 5
  • Hi, thanks for your answer, I implemented this and I can't upload images yet but the txt file changed to: -------------------------------28947758029299 Content-Disposition: form-data; name="name"; filename="test.txt" Content-Type: application/binary testing txt -------------------------------28947758029299-- – LeoTorres Jan 19 '17 at 11:54
  • I'm using agent email password for authentication in this request. would it work? as i see in documentation it is allowed for end users – coder771 Sep 28 '18 at 13:29
0

I had the same problem, Restsharp was sending the file as multipart, the only solution that worked for me was to send the file as parameter with content "application/binary".

public string UploadFile(ZendeskFile file)
{
    try
    {
        var request = new RestRequest(FileUploadsPath, Method.POST);
        request.AddQueryParameter("filename", file.Name);
        request.AddParameter("application/binary", file.Data, ParameterType.RequestBody);
        var response = Execute<UploadZendeskFileResponse>(request);
        var result = JsonConvert.DeserializeObject<UploadZendeskFileResponse>(response.Content);
        return result.upload.token;
    }
    catch (Exception ex)
    {
        throw ex;
    }

}

I hope this helps someone else.

0

In my case, I did something like this. Hope you won't waste 6 hours like me!

public async Task UploadImageToZendesk(IFormFile image)
    {
        byte[] fileByteArray;
        var request = new HttpRequestMessage();
        var client = new HttpClient();

        await using (var fileStream = image.OpenReadStream())
        await using (var memoryStream = new MemoryStream())
        {
            await fileStream.CopyToAsync(memoryStream);
            fileByteArray = memoryStream.ToArray();
        }

        ByteArrayContent byteContent = new ByteArrayContent(fileByteArray);
        request.Content = byteContent;
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse($"application/binary");

        await client.SendAsync(request);
    }