简体   繁体   English

上载pdf / doc等,并根据请求将数据发送到服务器-Javascript

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

I need to upload pdf,excelsheets,doc. 我需要上传pdf,excelsheets,doc。 etc format to server - data in request file using simple Javascript. 等格式到服务器-使用简单的Javascript将请求文件中的数据。 I was thinking to do with Blob , byte stream .. is it possible. 我当时想和Blob一起做,字节流..是否可能。 Can someone explain ? 有人可以解释吗?

Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice. 使用香草Javascript,您可以创建XMLHTTPRequest对象,并将文件发送到您选择的任何端点。

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. 如果这样,则可以使用FormData对象(它是已定义的键值对类型)来保存多个文件(如果您具有设置了multiple属性的HTML5 input表单)。 Make sure your project allows support for it . 确保您的项目允许它的支持
  • What server/framework are you using? 您正在使用什么服务器/框架? How do you access this? 您如何访问此内容? A request object? 一个request对象? Something similar? 相似的东西?
  • How do you want/need to create a selector for your html file input for use with Javascript? 您如何/需要为HTML文件输入创建选择器以与Javascript一起使用? I'll provide an example of using the html attribute of id below. 我将在下面提供一个使用id的html属性的示例。
  • Do you need to support CORS ? 您需要支持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. 如果是远程的,则需要在服务器中配置CORS

file input that allows multiple file support 允许多个文件支持的文件输入

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

javascript example javascript示例

// 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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