从 JQuery 中的文件输入获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12281775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:31:19  来源:igfitidea点击:

Get data from file input in JQuery

jqueryfilefile-uploadbase64html-input

提问by kschaeffler

I actually have a file input and I would like to retrieve the Base64 data of the file.

我实际上有一个文件输入,我想检索文件的 Base64 数据。

I tried:

我试过:

$('input#myInput')[0].files[0] 

to retrieve the data. But it only provides the name, the length, the content type but not the data itself.

来检索数据。但它只提供名称、长度、内容类型而不提供数据本身。

I actually need these data to send them to Amazon S3

我实际上需要这些数据将它们发送到 Amazon S3

I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.

我已经测试了 API,当我通过编码类型为“multipart/form-data”的 html 表单发送数据时,它可以工作。

I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload

我使用这个插件:http: //jasny.github.com/bootstrap/javascript.html#fileupload

And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.

这个插件为我提供了图片预览,我在图像预览的 src 属性中检索数据。但是当我将这些数据发送到 S3 时它不起作用。我可能需要对数据进行编码,如“multipart/form-data”,但我不知道为什么。

Is there a way to retrieve these data without using an html form?

有没有办法在不使用 html 表单的情况下检索这些数据?

回答by Morilog

input file element:

输入文件元素:

<input type="file" id="fileinput" />

get file :

获取文件:

var myFile = $('#fileinput').prop('files');

回答by Sark

You can try the FileReader API. Do something like this:

您可以尝试使用 FileReader API。做这样的事情:

<!DOCTYPE html>
<html>
    <head>
        <script>        
      function handleFileSelect()
      {               
        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
          alert('The File APIs are not fully supported in this browser.');
          return;
        }   

        var input = document.getElementById('fileinput');
        if (!input) {
          alert("Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
          alert("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
          alert("Please select a file before clicking 'Load'");               
        }
        else {
          var file = input.files[0];
          var fr = new FileReader();
          fr.onload = receivedText;
          //fr.readAsText(file);
          //fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
          fr.readAsDataURL(file);
        }
      }

      function receivedText() {
        document.getElementById('editor').appendChild(document.createTextNode(fr.result));
      }           

    </script>
    </head>
    <body>
        <input type="file" id="fileinput"/>
        <input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
        <div id="editor"></div>
    </body>
</html>

回答by mark.inman

I created a form data object and appended the file:

我创建了一个表单数据对象并附加了文件:

var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

and i got:

我得到了:

------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv

in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla

在发送的标头中。我可以确认这有效,因为我的文件已发送并存储在我服务器上的文件夹中。如果您不知道如何使用 FormData 对象,有一些在线文档,但不多。Mozilla 的表单数据对象解释

回答by cerbin

Html:

网址:

<input type="file" name="input-file" id="input-file">

jQuery:

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

我们只想获取第一个元素,因为 prop('files') 返回数组。

回答by Carlos B. Flores

inputelement, of type file

input元素,类型 file

<input id="fileInput" type="file" />

On your inputchange use the FileReaderobject and read your inputfile property:

在您input更改时使用FileReader对象并读取您的input文件属性:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.resultyou have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

FileReader 将加载您的文件,并且fileReader.result您拥有 Base64 格式的文件数据(还有文件内容类型 (MIME)、文本/纯文本、图像/jpg 等)

回答by shramee

FileReader API with jQuery, simple example.

带有 jQ​​uery 的 FileReader API,简单示例。

( function ( $ ) {
 // Add click event handler to button
 $( '#load-file' ).click( function () {
  if ( ! window.FileReader ) {
   return alert( 'FileReader API is not supported by your browser.' );
  }
  var $i = $( '#file' ), // Put file input ID here
   input = $i[0]; // Getting the element from jQuery
  if ( input.files && input.files[0] ) {
   file = input.files[0]; // The file
   fr = new FileReader(); // FileReader instance
   fr.onload = function () {
    // Do stuff on onload, use fr.result for contents of file
    $( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
   };
   //fr.readAsText( file );
   fr.readAsDataURL( file );
  } else {
   // Handle errors here
   alert( "File not selected or browser incompatible." )
  }
 } );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>

To read as text... uncomment //fr.readAsText(file);line and comment fr.readAsDataURL(file);

作为文本阅读...取消注释//fr.readAsText(file);行和注释fr.readAsDataURL(file);

回答by Amit Rana

 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

下载以上名为 fileinput 的文件,将路径添加到您的索引页面。

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>