从 JQuery 中的文件输入获取数据 [英] Get data from file input in JQuery

查看:44
本文介绍了从 JQuery 中的文件输入获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试过了:

$('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.

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

I actually need these data to send them to Amazon S3

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

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

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

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

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.

有没有办法不使用 html 表单来检索这些数据?

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

推荐答案

你可以试试 FileReader API.做这样的事情:

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

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

这篇关于从 JQuery 中的文件输入获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆