最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get file input value as binary data - Stack Overflow

programmeradmin10浏览0评论

How can I access the binary representation with JavaScript from a file uploaded with a file input?:

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

I can access the details of the uploaded file successfully with:

$('[name="image"]').get(0).files[0].name
// "2013-10-19 15.10.59.jpg"

$('[name="image"]').get(0).files[0].size
// 774016

$('[name="image"]').get(0).files[0].type
// "image/jpeg"

But not the real representation.

I found this tutorial that makes use of:

document.getElementById("photo").files[0].getAsBinary()

However, that method doesn't exists in my browser (Chrome Canary 34.0.1772.0 on OS X 10.9).

How can I access the binary representation with JavaScript from a file uploaded with a file input?:

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

I can access the details of the uploaded file successfully with:

$('[name="image"]').get(0).files[0].name
// "2013-10-19 15.10.59.jpg"

$('[name="image"]').get(0).files[0].size
// 774016

$('[name="image"]').get(0).files[0].type
// "image/jpeg"

But not the real representation.

I found this tutorial that makes use of:

document.getElementById("photo").files[0].getAsBinary()

However, that method doesn't exists in my browser (Chrome Canary 34.0.1772.0 on OS X 10.9).

Share Improve this question asked Jan 8, 2014 at 15:04 jviottijviotti 18.9k27 gold badges91 silver badges152 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

From https://developer.mozilla.org/en-US/docs/Web/API/File.getAsBinary

Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

It suggests:

Note: This method is obsolete; you should use the FileReader method readAsBinaryString() or readAsArrayBuffer() instead.

However, FileReader has several other read functions that might be more appropriate, like readAsDataURL() which lets you immediately use the file in web context (e.g as <img> src attribute), see the method listing for all options.

// Retrieve the first (and only, unless using the `multiple` attribute) File from the FileList object
const f = document.getElementById("photo").files[0]; 
    
if (f) {
  const reader = new FileReader();
  reader.onload = function(evt) { 
    const metadata = `name: ${f.name}, type: ${f.type}, size: ${f.size}, contents:`;
    const contents = evt.target.result;
    console.log(metadata, contents);
  };
  reader.readAsDataURL(f);
}

Use the readAsBinaryString method of the FileReader API

发布评论

评论列表(0)

  1. 暂无评论