生成文件并通过Javascript中的HTML表单上传

时间:2015-07-30 00:10:51

标签: javascript html json

客户端要求我正在开发的(仅限客户端)Web应用程序上传应用程序生成的JSON文件。我无法访问服务器端脚本的代码,该脚本处理将文件保存到正确的目录。我只能访问以下HTML表单,该表单发布到服务器端脚本:

<form enctype="multipart/form-data" acceptcharset="UTF-8" method="post" style="clear:left" action="/ajax/FileUploader.html?idToUse=attachment-1438128389605&amp;decompress=false&amp;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>

我的客户端应用已经可以通过HTTP身份验证访问服务器和此特定HTML表单。

是否可以生成JSON文件并将其作为文件附加到表单中?要求是这一切都是通过客户端JavaScript完成的。​​

1 个答案:

答案 0 :(得分:0)

我使用FormData interface for XMLHttpRequest解决了这个问题。这是我的解决方案:

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