Asana API - 通过Java向任务添加附件

时间:2015-03-06 08:58:55

标签: java attachment asana

我一直试图通过Asana API上传任务附件,但到目前为止还没有成功。使用curl我没有问题让这个工作:

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

但是我在通过Java执行它时遇到了麻烦。我找到的关于它的几篇帖子提到它应该是multipart / form-data,所以我一直在尝试不同版本的工作multipart / form-data上传代码,我曾在其他地方使用过。我一直收到回复:

file: Missing input

基本上,代码如下所示:

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();

我尝试更改filePath以包含预期参数的JSON(来自我已阅读的其他帖子),例如:

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

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

其他变种。似乎没有什么工作,我不确定下一步该尝试什么。

1 个答案:

答案 0 :(得分:0)

这看起来类似于之前关于SO的问题:Asana Api Rails Attachment

请注意,文件上载中的文件需要作为表单编码的POST正文发送, not 作为JSON正文中的字符串发送。当浏览器发送它时,它会模拟正常的基于表单的文件上传。您的Java库可能具有这样的功能。 curl中的@符号实际上并不是上传的一部分 - 它只是告诉卷曲&#34;在这里包含一个文件&#34;。