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

How to convert string to File object in javascript ? - Stack Overflow

programmeradmin4浏览0评论

I am trying to convert string to File object in javascript but I get an error.

my code:

 var contents = fs.readFileSync('./dmv_file_reader.txt').toString()

 var  readerfile1 = new File([""], contents);

(i have to use contents as file and not as string)

and my output is :

ReferenceError: File is not defined
    at d:\Workspace\DMV\dist\win-ia32-unpacked\resources\app.asar\main.js:67:32
    at process._tickCallback (internal/process/next_tick.js:103:7)

any solution some1?

I am trying to convert string to File object in javascript but I get an error.

my code:

 var contents = fs.readFileSync('./dmv_file_reader.txt').toString()

 var  readerfile1 = new File([""], contents);

(i have to use contents as file and not as string)

and my output is :

ReferenceError: File is not defined
    at d:\Workspace\DMV\dist\win-ia32-unpacked\resources\app.asar\main.js:67:32
    at process._tickCallback (internal/process/next_tick.js:103:7)

any solution some1?

Share Improve this question asked Nov 29, 2016 at 15:31 Tom CohenTom Cohen 1632 gold badges4 silver badges12 bronze badges 7
  • Seems that the File object is not defined... Might have to require something from a module? – Jite Commented Nov 29, 2016 at 15:34
  • 1 There is no File object in node (assuming this is node since you're using fs). What are you trying to do with the file? – xdumaine Commented Nov 29, 2016 at 15:34
  • Have a look at: stackoverflow.com/questions/8390855/… ; Have you tried using the blob? – user6035379 Commented Nov 29, 2016 at 15:34
  • maybe : stackoverflow.com/questions/10654971/… – epascarello Commented Nov 29, 2016 at 15:35
  • In my code i have this line: code reader.readAsArrayBuffer(changeEvent.target.files[0]); code and then i send it to a function that get 'ArrayBuffer'. as i see here this function convert 'File' to 'ArrayBuffer'. therefor i want to convert my 'String' to 'File' and then use this function above. – Tom Cohen Commented Nov 29, 2016 at 15:44
 |  Show 2 more comments

1 Answer 1

Reset to default 17

First you have to create blob from Javascript object and that blob object can be passed to File() constructor to create a File Object.Hope this helps.

 var contents = fs.readFileSync('./dmv_file_reader.txt').toString()
 var blob = new Blob([contents], { type: 'text/plain' });
 var file = new File([blob], "foo.txt", {type: "text/plain"});
发布评论

评论列表(0)

  1. 暂无评论