从JQuery文件输入中获取数据

时间:2022-11-28 03:35:04

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进行了测试,当我通过html表单发送数据时,会使用编码类型的“multipart/form-data”进行编码。

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表单就能检索这些数据的方法?

7 个解决方案

#1


100  

you can try FileReader API 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;
    }   

    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 {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      //fr.readAsText(file);
      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


98  

input file element:

输入文件元素:

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

get file :

获取文件:

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

#3


39  

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形成数据对象解释

#4


7  

FileReader API with jQuery, simple example.

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

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

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

#5


6  

Html:

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')返回数组。

#6


5  

input element, of type file

输入元素,类型文件

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

On your input change use the FileReader object and read your input file property:

在输入更改时,使用FileReader对象并读取输入文件属性:

$('#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.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

FileReader将加载您的文件和FileReader。结果您有Base64格式的文件数据(也有文件内容类型(MIME)、文本/纯文本、图像/jpg等)

#7


1  

 <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的文件,添加您的索引页路径i。

<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


100  

you can try FileReader API 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;
    }   

    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 {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      //fr.readAsText(file);
      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


98  

input file element:

输入文件元素:

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

get file :

获取文件:

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

#3


39  

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形成数据对象解释

#4


7  

FileReader API with jQuery, simple example.

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

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

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

#5


6  

Html:

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')返回数组。

#6


5  

input element, of type file

输入元素,类型文件

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

On your input change use the FileReader object and read your input file property:

在输入更改时,使用FileReader对象并读取输入文件属性:

$('#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.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

FileReader将加载您的文件和FileReader。结果您有Base64格式的文件数据(也有文件内容类型(MIME)、文本/纯文本、图像/jpg等)

#7


1  

 <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的文件,添加您的索引页路径i。

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