简体   繁体   中英

uploading pdf/doc etc and sending data to the server in request - Javascript

I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript. I was thinking to do with Blob , byte stream .. is it possible. Can someone explain ?

Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.

Some questions to consider when you are working doing this:

  • Are you looking to upload just the file or do you need to upload any associated data with it?
  • Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it .
  • What server/framework are you using? How do you access this? A request object? Something similar?
  • How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
  • Do you need to support CORS ? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.

file input that allows multiple file support

<input type='file' id='multiple-file-input' multiple>

javascript example

// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to

var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';

var formdata = new FormData();     // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable

// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {

    // Appending each file to FormData object
    // sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
    formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);

}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr); // log response object
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM