File Upload
Steps
- Create a project file_upload_project
- Then create a JavaScript service named my_file_upload.js
- Replace the service code with the following content:
File Upload Handler
var upload = require('http/v4/upload');
var request = require('http/v4/request');
var response = require('http/v4/response');
if (request.getMethod() === "POST") {
if (upload.isMultipartContent()) {
var fileItems = upload.parseRequest();
for (i=0; i<fileItems.size(); i++) {
var fileItem = fileItems.get(i);
if (!fileItem.isFormField()) {
response.println("File Name: " + fileItem.getName());
response.println("File Bytes (as text): " + String.fromCharCode.apply(null, fileItem.getBytes()));
} else {
response.println("Field Name: " + fileItem.getFieldName());
response.println("Field Text: " + fileItem.getText());
}
}
} else {
response.println("The request's content must be 'multipart'");
}
} else if (request.getMethod() === "GET") {
response.println("Use POST request.");
}
response.flush();
response.close();
- Then create a HTML5 page named my_upload.html
- Replace the content with the following HTML code:
File Upload Frontend
<html>
<body>
<form action="/services/v4/js/file_upload_project/my_file_upload.js" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" multiple>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
- Publish the project
- Select the my_upload.html file in the Workspace view and try to test by uploading a file in the Preview
For more information, see the API documentation.