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!
Hi everyone, I have found a better solution.
I write the code below:
<div class="field-group">
<label for="ffi1">Add file</label>
<label class="ffi" data-ffi-button-text="Browse">
<input type="file" id="file" name="file" aria-label="Add file">
</label>
</div>
Here the magic:
var file= $('input#file')[0].files[0];
var formData = new FormData();
formData.append( "file" , file, file.name );
$.ajax({
url: AJS.contextPath() + "/rest/api/2/issue/{ISSUE-ID}/attachments" ,
type: "POST" ,
data: formData,
headers: {
"X-Atlassian-Token" : "nocheck"
},success:
function
(response) {
console.log( "response[0].id" );
},error:
function
(jqXHR, textStatus, errorThrown) {
console.log( "error" );
},
contentType: false,
processData: false
});
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.