IT story

JavaScript에서 File 객체를 인스턴스화하는 방법은 무엇입니까?

hot-time 2020. 7. 9. 07:59
반응형

JavaScript에서 File 객체를 인스턴스화하는 방법은 무엇입니까?


FileJavaScript 에는 객체가 있습니다. 테스트 목적으로 인스턴스화하고 싶습니다.

시도 new File()했지만 "잘못된 생성자"오류가 발생합니다.

File객체 를 만들 수 있습니까?


파일 객체 참조 : https://developer.mozilla.org/en/DOM/File


W3C File API 스펙에 따르면 File 생성자는 2 (또는 3) 개의 매개 변수를 필요로합니다.

빈 파일을 만들려면 다음을 수행하십시오.

var f = new File([""], "filename");
  • 첫 번째 인수는 텍스트 줄의 배열로 제공되는 데이터입니다.
  • 두 번째 인수는 파일 이름입니다.
  • 세 번째 인수는 다음과 같습니다.

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

FireFox, Chrome 및 Opera에서는 작동하지만 Safari 또는 IE / Edge에서는 작동하지 않습니다.


이제 할 수 있습니다!

var parts = [
  new Blob(['you construct a file...'], {type: 'text/plain'}),
  ' Same way as you do with blob',
  new Uint16Array([33])
];

// Construct a file
var file = new File(parts, 'sample.txt', {
    lastModified: new Date(0), // optional - default = now
    type: "overide/mimetype" // optional - default = ''
});

var fr = new FileReader();

fr.onload = function(evt){
   document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate
}

fr.readAsText(file);


최신 정보

테스트 목적으로 BlobBuilder를 사용하는 경우 BlobBuilder는 더 이상 사용되지 않습니다 .

그렇지 않으면 이 질문에 대한 답변과 같이 Blob 으로 이동하는 마이그레이션 전략을 아래에 적용하십시오 .

대신 Blob을 사용하십시오.

대안으로이 물방울을 당신이 대신 사용할 수있는 파일 그대로 어떤 당에서 파일 인터페이스 도출 W3C 사양 :

interface File : Blob {
    readonly attribute DOMString name;
    readonly attribute Date lastModifiedDate;
};

File 인터페이스는 Blob을 기반으로하며 Blob 기능을 상속하고 사용자 시스템의 파일을 지원하도록 확장합니다.

얼룩 만들기

파일을 업로드 하고 Blob을 제공 하는 기존 JavaScript 메소드 에서 BlobBuilder를 이와 같이 사용하면 다음 과 같이 XMLHttpRequest작동합니다.

var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);

xhr.responseType = 'arraybuffer';

bb.append(this.response); // Note: not xhr.responseText

//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');

/* more setup code */
xhr.send(blob);

Extended example

The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.


Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

The idea ...To create a File object (api) in javaScript for images already present in the DOM :

<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">

var file = new File(['fijRKjhudDjiokDhg1524164151'],
                     '../img/Products/fijRKjhudDjiokDhg1524164151.jpg', 
                     {type:'image/jpg'});

// created object file
console.log(file);

Don't do that ! ... (but I did it anyway)

-> the console give a result similar as an Object File :

File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File

But the size of the object is wrong ...

Why i need to do that ?

For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update


Because this is javascript and dynamic you could define your own class that matches the File interface and use that instead.

I had to do just that with dropzone.js because I wanted to simulate a file upload and it works on File objects.

참고URL : https://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript

반응형