0

I have been trying to upload an attachment to a task through the Asana API and am so far unsuccessful. Using curl I had no problem getting this working:

curl -u <api_key>: --form "file=@<path_to_file>" https://app.asana.com/api/1.0/tasks/<task_id>/attachments

But I am having trouble executing it through Java. The few posts I found about it mentioned that it should be multipart/form-data so I've been trying different versions of working multipart/form-data upload code that I have used elsewhere. I keep getting the response back:

file: Missing input

Basically, the code looks like this:

Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "multipart/form-data");
headers.put("Authorization", "Basic " + encodedCreds);
Path p = Paths.get(filePath);
String fileName = p.getFileName().toString();
headers.put("Content-Disposition", "form-data; name=\"" + "file" + "\"; filename=\"" + fileName + "\"");

url = new URL(urlStr);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod(method);

if(headers != null) {
    for(Map.Entry<String, String> headerEntry : headers.entrySet()){
        conn.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
    }
}

conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
FileInputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    wr.write(buffer, 0, bytesRead);
}
inputStream.close();
wr.flush();
wr.close();

I've tried altering filePath to include JSON of what the expected parameters seem to be (from other posts I've read) such as:

{"data" : { "id": <taskId> , "file" : @<filePath> } }

or

{"files" : { "file" : @<filePath> } }

And other variations of that. Nothing seems to be working and I'm not sure what to try next.

Abe Hendlish
  • 707
  • 5
  • 11

1 Answers1

0

This looks similar to a previous question on SO: Asana Api Rails Attachment

Note that the file in a file upload needs to be sent as a form-encoded POST body, not as a string in a JSON body. It's emulating a normal form-based file upload as a browser would send it. Your Java library probably has the ability to do something like this. The @ symbol in curl isn't actually part of the upload - it's just telling curl "include a file here".

Community
  • 1
  • 1
agnoster
  • 3,744
  • 2
  • 21
  • 29