6

Let's say I want to use some js encryption library (not java) to encrypt a file. Is it possible to do so on client side before sending the file to the server and so upload a file by javascript in some memory on client side ?

Could I use local storage for example at least for latest browsers ?

user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

6

You could use the File API

Here some examples: https://developer.mozilla.org/en/Using_files_from_web_applications)

Of course, as you imagined, you need latest browsers.

ZER0
  • 24,846
  • 5
  • 51
  • 54
  • 4
    This answer should have some code showing what to do, link only answers are not as useful, I'm not sure what part of that link talks about uploading an in memory file... – Ruan Mendes Oct 16 '17 at 15:04
2

Yes you can. You have a few options to do that though.

Using FormData

const formData = new FormData()
formData.append('file', new Blob([fileTextContent], {type: 'text/plain'}))
await axios.post('/upload-file', formData)

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#creating_a_formdata_object_from_scratch

Set a file <input>'s value

let file = new File([data], "img.jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
let container = new DataTransfer();
container.items.add(file);
fileInputElement.files = container.files;

Then you can submit the form containing the <input> normally.

The code above is from this SO answer: https://stackoverflow.com/a/66466855/14366961

Khanh Luong
  • 418
  • 4
  • 7