使用JQuery从文件输入获取数据

188

我实际上有一个文件输入框,我想要获取该文件的Base64数据。

我尝试过:

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

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

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

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

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

这个插件给我提供了图片预览,并从图像预览的src属性中检索数据。但当我将这些数据发送到S3时,它不起作用。我可能需要像"multipart/form-data"这样对数据进行编码,但我不知道原因。

有没有一种方法可以不使用html表单来检索这些数据?


为了拥有内容,你需要通过某种方式上传它(iframe、ajax、flash或传统表单)。 - Brad Christie
1
文件必须先上传到服务器。 - Sven van Zoelen
7
如果浏览器支持新的文件API(参见http://www.html5rocks.com/en/tutorials/file/dndfiles/),就不一定需要这样做。 - devnull69
我实际上正在使用这个插件http://jasny.github.com/bootstrap/javascript.html#fileupload,我可以预览文件,因此数据在某个地方。 - kschaeffler
在这种情况下,“数据”将位于服务器上。您必须先将数据输出到客户端(浏览器),然后才能通过Javascript / jQuery访问它。 - devnull69
我认为我使用的插件已经可以做到这一点了。我可以在图像预览文件中检索到一些数据,但那只是部分数据,而不是所有文件数据。 - kschaeffler
10个回答

243

输入文件元素:

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

获取文件:

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

24
完美的解决方案!谢谢你。 针对单个上传,第一项的改进。 var myFile = $('#fileinput').prop('files')[0]; - polras
太棒了,我成功地使用Cloudinary脚本而无需提交表单。拖放,上传 :) - Andy
那正是我所需要的。 - Helen Araya
非常好的答案!!然后你可以使用 $('.myClass').prop('files', myFile ); 将变量移动。 - always-a-learner

157
你可以尝试使用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>


1
嘿,我尝试了你的解决方案,它有效。我检索到了信息,但它没有被很好地编码。对于一个文件,我得到了\xc3\xbf\xc3而不是获取我的图片前三个字符的这个编码\xff\xd8\xff。我应该使用什么来获取我的图片的第二个编码? - kschaeffler
@kschaeffler 尝试使用 fr.readAsDataURL(file); 这个函数来读取Base64数据,不过我还没有测试过。 - Sark
1
实际上,这个函数给我的数据不够。这已经是我从插件jasny.github.com/bootstrap/javascript.html#fileupload中使用的预览中所拥有的了。我认为我检索到的数据没有进行Base64编码,这就是问题所在,但我不确定。 - kschaeffler
我实际上需要与使用“multipart/form-data”编码类型通过HTML表单提交时检索到的相同编码数据。 - kschaeffler

54
我创建了一个表单数据对象并附加了文件:
var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

我得到了:

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

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

Mozilla的Form Data对象说明

49

Html:

Html:

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

jQuery:

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

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


22

输入 元素,类型为 文件

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

在您的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将加载您的文件,在fileReader.result中,您可以获得Base64格式的文件数据(还有文件内容类型(MIME),text/plain,image/jpg等)。


17

使用jQuery的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>

如果要将文件内容作为文本读取,请取消注释//fr.readAsText(file);并注释掉fr.readAsDataURL(file);


6

使用 jQuery 获取文件

HTML 元素:

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

JQuery 代码:

 $("#fileInput")[0].files[0]

这对我很有效 :)

1

HTML

<div class="row form-group my-2">
                <div class="col-12">
                    <div class="">
                        <div class="text-center">
                            <label for="inpImage" class="m-2 pointer">
                                <img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
                            </label>
                            <input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
                        </div>
                    </div>
                </div>
            </div>

jQuery

$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});

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

下载上述名为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>

-1

<!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>


2
你可以提供一个解决方案的例子,并说明它如何帮助问题的提出者,从而改进你的回答。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接