Hi community,
I'm trying to attach images using the API.
The problem seems to be how I pass the file from js to java.
Running the following code I find an attachment on my issue, but it is impossible to view it:
It appears that we don't support this file format
This is my code:
SOY:
<div class="field-group">
<label for="ffi1">File Input</label>
<label class="ffi" data-ffi-button-text="Browse">
<input type="file" id="file" name="file" aria-label="File Input">
</label>
</div>
<input class="hidden" type="submit" id="hidden-submit" name="hidden-submit" />
JS:
var documentData = new FormData();
documentData.append('file', $('input#file')[0].files[0]);
$.ajax({
url: this.baseUrl + 'expense/attachment',
type: 'POST',
data: documentData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
alert("Document uploaded successfully.");
}
});
Java:
@POST
@Path("attachment")
@Consumes({"application/x-www-form-urlencoded", "multipart/form-data"})
public Response addAttachment(InputStream uploadedInputStream) throws IOException {
File file = new File("Expense-"+new Date().getTime()+".jpg");
OutputStream fos = new FileOutputStream(file);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.writeTo(fos);
AttachmentManager attachmentManager = ComponentAccessor.getAttachmentManager();
IssueManager issueManager = ComponentAccessor.getIssueManager();
Issue issue = issueManager.getIssueByCurrentKey("SIRORD-2");
ChangeItemBean changeItemBean = attachmentManager.createAttachment(new CreateAttachmentParamsBean(file, file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), null, issue, false, false, null, new Date(), false));
return Response.ok().build();
} catch (NumberFormatException | AttachmentException e) {
return Response.status(Status.NOT_FOUND).build();
} finally {
fos.close();
}
}
I tried also to change che contentType from false to "multipart/form-data" but nothing changed.
Where am I doing wrong?
Thank you!