Reputation: 3035
A client requires that the (client-side only) web app which I am developing uploads a JSON file generated by the app. I have no access to the code of the server-side script which handles the saving of the file to the correct directory. I only have access to the following HTML form which posts to the server-side script:
<form enctype="multipart/form-data" acceptcharset="UTF-8" method="post" style="clear:left" action="/ajax/FileUploader.html?idToUse=attachment-1438128389605&decompress=false&outputLocation=%2Fusr%2Flocal%2Ftomcat%2Fwebapps%2FROOT%2Fimages%2F">
<input size="50" type="file" name="attachment-1438128389605">
<div style="padding-top:5px">
<div style="display:none; margin-left:60px; margin-top:10px; float:left" class="file-type-not-permitted">This file type is not permitted </div>
<input type="submit" name="upload" value="Upload" class="ui-widget ui-state-default ui-corner-all ui-button-disabled ui-state-disabled input-type-submit-small" role="button" aria-disabled="true" disabled="">
</div>
</form>
My client-side app already has access to the server and this particular HTML form via HTTP authentication.
Is it possible to generate the JSON file and attach it as file to the form? The requirement is that this is all done through client-side JavaScript.
Upvotes: 1
Views: 1153
Reputation: 3035
I solved the problem by using the FormData interface for XMLHttpRequest. Here is my solution:
// Set the folder path where the file will be uploaded:
var encodedFolderPath =
encodeURIComponent('/usr/local/tomcat/webapps/ROOT/images/');
// Set the file name of the file to be uploaded:
var encodedFileName = encodeURIComponent('my_file' + '.json');
// Set the file input name to a unique value (required by the server):
var attachment = "attachment-" + (new Date()).getTime();
// Construct the form data:
var formData = new FormData();
// Construct a JavaScript file-like object
var content = "{ json content here }";
var blob = new Blob([content], { type: "application/octet-stream"});
formData.append(attachment, blob, encodedFileName);
// Set the upload URL:
var uploadURL = "";
uploadURL = '/ajax/FileUploader.html?idToUse=' + attachment +
'&decompress=false&outputLocation=' +
encodedFolderPath + '&fileName=' + encodedFileName;
// Send the request:
var request = new XMLHttpRequest();
request.open("POST", uploadURL);
request.send(formData);
Upvotes: 3