Getting byte array through input type = file
read file bytes in javascript
readasarraybuffer
convert file to byte array angular 2
convert file to binary javascript
get file from byte array javascript
javascript create file object from local path
filereader example
var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in WebAPI [HttpPost] public HttpResponseMessage UpdateProfile([FromUri]UpdateProfileModel response) { //... return response; } public class UpdateProfileModel { // ... public byte[] ProfileImage {get ;set; } // ... }
<input type="file" id="inputFile" />
[Edit]
As noted in comments above, while still on some UA implementations, readAsBinaryString
method didn't made its way to the specs and should not be used in production.
Instead, use readAsArrayBuffer
and loop through it's buffer
to get back the binary string :
document.querySelector('input').addEventListener('change', function() { var reader = new FileReader(); reader.onload = function() { var arrayBuffer = this.result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array); console.log(binaryString); } reader.readAsArrayBuffer(this.files[0]); }, false);
<input type="file" /> <div id="result"></div>
File.getAsBinary(), The getAsBinary method allows to access the file's data in raw binary format. use the FileReader method readAsBinaryString() or readAsArrayBuffer() instead. fileInput is an HTMLInputElement: <input type="file" id="myfileinput" Get the latest and greatest from MDN delivered straight to your inbox. I try to convert a file that i get through an input file into a byte[]. I tried with a FileReader, but i must miss something : var bytes = []; var reader = new FileReader(); reader.onload = function { bytes = reader.result; }; reader.readAsArrayBuffer(myFile); But in the end, my bytes var doesn't content a byte array.
$(document).ready(function(){ (function (document) { var input = document.getElementById("files"), output = document.getElementById("result"), fileData; // We need fileData to be visible to getBuffer. // Eventhandler for file input. function openfile(evt) { var files = input.files; // Pass the file to the blob, not the input[0]. fileData = new Blob([files[0]]); // Pass getBuffer to promise. var promise = new Promise(getBuffer); // Wait for promise to be resolved, or log error. promise.then(function(data) { // Here you can pass the bytes to another function. output.innerHTML = data.toString(); console.log(data); }).catch(function(err) { console.log('Error: ',err); }); } /* Create a function which will be passed to the promise and resolve it when FileReader has finished loading the file. */ function getBuffer(resolve) { var reader = new FileReader(); reader.readAsArrayBuffer(fileData); reader.onload = function() { var arrayBuffer = reader.result var bytes = new Uint8Array(arrayBuffer); resolve(bytes); } } // Eventlistener for file input. input.addEventListener('change', openfile, false); }(document)); });
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <input type="file" id="files"/> <div id="result"></div> </body> </html>
Working with Files in JavaScript, There are many ways to read a file using JavaScript APIs - to a data URL, 01 November 2016 on javascript, blob, file, arraybuffer, buffer, Getting the File from the ListList object, which originates from an <input type="file"> element: and increasing the value of every second byte (the green value). Call the File.ReadAllBytes method in System.IO to get a byte array from a file. File.ReadAllBytes returns a byte array. It is simple to call—it receives a filename and returns the file data. It can be combined with other types to create high performance file formats.
This is a long post, but I was tired of all these examples that weren't working for me because they used Promise objects or an errant this
that has a different meaning when you are using Reactjs. My implementation was using a DropZone with reactjs, and I got the bytes using a framework similar to what is posted at this following site, when nothing else above would work: https://www.mokuji.me/article/drop-upload-tutorial-1 . There were 2 keys, for me:
- You have to get the bytes from the event object, using and during a FileReader's onload function.
I tried various combinations, but in the end, what worked was:
const bytes = e.target.result.split('base64,')[1];
Where e
is the event. React requires const
, you could use var
in plain Javascript. But that gave me the base64 encoded byte string.
So I'm just going to include the applicable lines for integrating this as if you were using React, because that's how I was building it, but try to also generalize this, and add comments where necessary, to make it applicable to a vanilla Javascript implementation - caveated that I did not use it like that in such a construct to test it.
These would be your bindings at the top, in your constructor, in a React framework (not relevant to a vanilla Javascript implementation):
this.uploadFile = this.uploadFile.bind(this); this.processFile = this.processFile.bind(this); this.errorHandler = this.errorHandler.bind(this); this.progressHandler = this.progressHandler.bind(this);
And you'd have onDrop={this.uploadFile}
in your DropZone element. If you were doing this without React, this is the equivalent of adding the onclick event handler you want to run when you click the "Upload File" button.
<button onclick="uploadFile(event);" value="Upload File" />
Then the function (applicable lines... I'll leave out my resetting my upload progress indicator, etc.):
uploadFile(event){ // This is for React, only this.setState({ files: event, }); console.log('File count: ' + this.state.files.length); // You might check that the "event" has a file & assign it like this // in vanilla Javascript: // var files = event.target.files; // if (!files && files.length > 0) // files = (event.dataTransfer ? event.dataTransfer.files : // event.originalEvent.dataTransfer.files); // You cannot use "files" as a variable in React, however: const in_files = this.state.files; // iterate, if files length > 0 if (in_files.length > 0) { for (let i = 0; i < in_files.length; i++) { // use this, instead, for vanilla JS: // for (var i = 0; i < files.length; i++) { const a = i + 1; console.log('in loop, pass: ' + a); const f = in_files[i]; // or just files[i] in vanilla JS const reader = new FileReader(); reader.onerror = this.errorHandler; reader.onprogress = this.progressHandler; reader.onload = this.processFile(f); reader.readAsDataURL(f); } } }
There was this question on that syntax, for vanilla JS, on how to get that file object:
JavaScript/HTML5/jQuery Drag-And-Drop Upload - "Uncaught TypeError: Cannot read property 'files' of undefined"
Note that React's DropZone will already put the File object into this.state.files
for you, as long as you add files: [],
to your this.state = { .... }
in your constructor. I added syntax from an answer on that post on how to get your File object. It should work, or there are other posts there that can help. But all that Q/A told me was how to get the File
object, not the blob data, itself. And even if I did fileData = new Blob([files[0]]);
like in sebu's answer, which didn't include var
with it for some reason, it didn't tell me how to read that blob's contents, and how to do it without a Promise object. So that's where the FileReader came in, though I actually tried and found I couldn't use their readAsArrayBuffer
to any avail.
You will have to have the other functions that go along with this construct - one to handle onerror
, one for onprogress
(both shown farther below), and then the main one, onload
, that actually does the work once a method on reader
is invoked in that last line. Basically you are passing your event.dataTransfer.files[0]
straight into that onload
function, from what I can tell.
So the onload
method calls my processFile()
function (applicable lines, only):
processFile(theFile) { return function(e) { const bytes = e.target.result.split('base64,')[1]; } }
And bytes
should have the base64 bytes.
Additional functions:
errorHandler(e){ switch (e.target.error.code) { case e.target.error.NOT_FOUND_ERR: alert('File not found.'); break; case e.target.error.NOT_READABLE_ERR: alert('File is not readable.'); break; case e.target.error.ABORT_ERR: break; // no operation default: alert('An error occurred reading this file.'); break; } } progressHandler(e) { if (e.lengthComputable){ const loaded = Math.round((e.loaded / e.total) * 100); let zeros = ''; // Percent loaded in string if (loaded >= 0 && loaded < 10) { zeros = '00'; } else if (loaded < 100) { zeros = '0'; } // Display progress in 3-digits and increase bar length document.getElementById("progress").textContent = zeros + loaded.toString(); document.getElementById("progressBar").style.width = loaded + '%'; } }
And applicable progress indicator markup:
<table id="tblProgress"> <tbody> <tr> <td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td> </tr> </tbody> </table>
And CSS:
.progressBar { background-color: rgba(255, 255, 255, .1); width: 100%; height: 26px; } #progressBar { background-color: rgba(87, 184, 208, .5); content: ''; width: 0; height: 26px; }
EPILOGUE:
Inside processFile()
, for some reason, I couldn't add bytes
to a variable I carved out in this.state
. So, instead, I set it directly to the variable, attachments
, that was in my JSON object, RequestForm
- the same object as my this.state
was using. attachments
is an array so I could push multiple files. It went like this:
const fileArray = []; // Collect any existing attachments if (RequestForm.state.attachments.length > 0) { for (let i=0; i < RequestForm.state.attachments.length; i++) { fileArray.push(RequestForm.state.attachments[i]); } } // Add the new one to this.state fileArray.push(bytes); // Update the state RequestForm.setState({ attachments: fileArray, });
Then, because this.state
already contained RequestForm
:
this.stores = [ RequestForm, ]
I could reference it as this.state.attachments
from there on out. React feature that isn't applicable in vanilla JS. You could build a similar construct in plain JavaScript with a global variable, and push, accordingly, however, much easier:
var fileArray = new Array(); // place at the top, before any functions // Within your processFile(): var newFileArray = []; if (fileArray.length > 0) { for (var i=0; i < fileArray.length; i++) { newFileArray.push(fileArray[i]); } } // Add the new one newFileArray.push(bytes); // Now update the global variable fileArray = newFileArray;
Then you always just reference fileArray
, enumerate it for any file byte strings, e.g. var myBytes = fileArray[0];
for the first file.
Get byte[] from uploaded file : javascript, I want to be able to upload a file from the client that sombody drops in(like a and with data i mean byte[] Like if i use C# and use System.IO.File.ReadAllBytes( "file"); responseType = 'arraybuffer' responseType = 'blob' id="dropzone"> Drop files here</div> </body> <script type="text/javascript"> var dropzone = document� Do it in two parts, get the file first, then get the byte array from the file. Have a look at this tutorial for getting the file. Fie upload to Sevlets. Then look at this trail from the Oracle site for IO and byte streams. Once you've worked through both you should be able to work it out. Basic I/O
This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.
document.querySelector('#fileInput').addEventListener('change', function () { var reader = new FileReader(); var selectedFile = this.files[0]; reader.onload = function () { var comma = this.result.indexOf(','); var base64 = this.result.substr(comma + 1); console.log(base64); } reader.readAsDataURL(selectedFile); }, false);
<input id="fileInput" type="file" />
Read files in JavaScript, How to select files, read file metadata and content, and monitor read The easiest way to allow users to select files is using the <input type="file"> element, which is Unfortunately, today there isn't a good way to get access to a directory. You can instruct FileReader to read a file as an array buffer, a data� This byte array can be used to pass through network as well as other program APIs for further processing. Let’s learn about few ways of reading data from files into byte array in java. 1. Read file to byte[] array with NIO [Java 7 and later] Files.readAllBytes() is best method if you are using java 7. Otherwise you will need any method from
document.querySelector('input').addEventListener('change', function(){ var reader = new FileReader(); reader.onload = function(){ var arrayBuffer = this.result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array); console.log(binaryString); console.log(arrayBuffer); document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength; } reader.readAsArrayBuffer(this.files[0]); }, false);
<input type="file"/> <div id="result"></div>
File Upload Via Byte Array Transfer � Issue #7660 � dotnet , Describe the bug I am currently trying to get file uploading Other Directives *@ @inject IJSRuntime Runtime @* Markup *@ <input type="file"� - Java - How to convert File to byte[]
File API, The user interface for selection can be invoked via <input type="file"> A Blob blob has an associated get stream algorithm, which runs Enqueue a Uint8Array object wrapping an ArrayBuffer containing bytes into stream . We’ll receive the file binary as base64 from the javascript function because byte arrays are not serializable in json and this is the format of exchange between C# and js. the api will just send back the file name where the file is saved, but you can do what you want. JS side. Here is the method for getting the file content
HttpPostedFile.InputStream Property (System.Web), Gets a Stream object that points to an uploaded file to prepare for reading the Read(input, 0, FileLen); // Copy the byte array into a string. for (int Loop1 = 0;� In this quick tutorial, we're going to show how to convert a File to an InputStream – first using plain Java and then Guava and the Apache Commons IO library. This article is part of the “ Java – Back to Basic ” series here on Baeldung.
FileUpload.FileContent Property (System.Web.UI.WebControls , Gets a Stream object that points to a file to upload using the FileUpload control. fileLen; StringBuilder displayString = new StringBuilder(); // Get the length of the file. Read(Input, 0, fileLen); // Copy the byte array to a string. for (int loop1 = 0;� You can specify a filter to the Get-Content cmdlet. When using filters to qualify the Path parameter, you need to include a trailing asterisk (*) to indicate the contents of the path. The following command gets the content of all *.log files in the C:\Temp directory. Get-Content -Path C:\Temp\* -Filter *.log Example 8: Get file contents as a byte array
Comments
- you need to share your code... server side and client side
- @ArunPJohny i have updated the code. note that i am not allow to use server side solution to get byte array of input file before posting
- Please visit this link : stackoverflow.com/questions/31433413/…
- Related - stackoverflow.com/questions/47574218/…
- To Arun's point, there's literally nothing here for getting the input bytes. No attempt made. The code above is the sending/receiving code, only, which is largely irrelevant to this question. To me, that deserves a downvote on the question. It's an important question, deserving of an answer, but it requires a lengthy answer just to get a person up to speed. It's like asking "How do I pilot a plane" instead of "What are the parameters I need to know in order to know if I can take off?"
- how do i assign the readAsArrayBuffer result and pass through ajax call?
- in the reader load event, call your ajax function with the arraybuffer as argument (
reader.onload = function(){ yourAwesomeAjaxFunction(this.result)};
and thenfunction yourAwesomeAjaxFunction( profileImage ){ $.ajax({ url: 'abc.com/',...
- it seems that the request accepted by web api is null. however, i got the length display. How can i output the display of arraybuffer in alert form ?
arrayBuffer.byteLength
it's in the code snippet I gave you- this has no support for ie and is deprecated. i would suggest switching to the mentioned method: readAsArrayBuffer
- Note that versions of IE before 11, I believe, don't support the use of
Promise
objects. - hi sebu.. Thanks for this answer.. this seems to work for me.. but, which of
arrayBuffer
andbytes
is the byte array? Ifbytes
is(as per the name), then what isarrayBuffer
? @vapcguy, would be really grateful if you could help me out too here.. - @Rai
arrayBuffer
would probably be the one you want, but when I was looking at this, I couldn't figure it out, either, and went my own way withreader.readAsDataURL(f);
(instead ofreader.readAsArrayBuffer(fileData);
) where I usedvar f = files[0];
, which is similar tofileData
above except I didn't cast it to aBlob
first. I provided an answer on this question, too, and it was written for React originally, but a careful reading of it will give you a vanilla JS version, too.