Getting Byte Array Through Input Type = File

Getting byte array through input type = file

[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>

jQuery read byte[] from type=file input box on submit

You could use form submit or use ajax to post the form and use IFormFile on action to receive your file.In the action, then you could get file name or convert file to byte[].

The name of action parameter is required to match the name of form data.

For example:

Js:

<script>
$('#submitAddFile').click(function (e) {
e.preventDefault();
var file = $('#fileInput')[0].files;
var formData = new FormData();
formData.append("myFile", file[0]);


$.ajax({
type: "POST",
url: "/Home/UploadFile",
contentType: false,
processData: false,
data: formData,
success: function (result) {
alert("success");
},
error: function () {
alert("there was an error");
}
});
})
</script>

HomeController:

[HttpPost]
public void UploadFile(IFormFile myFile)
{
var fileName = Path.GetFileName(myFile.FileName);
using (var ms = new MemoryStream())
{
myFile.CopyTo(ms);
byte[] fileBytes = ms.ToArray();

//save fileName and fileBytes into database
}

}

Convert System.Byte[] to HTML Input type=FILE

As explained by @Stephen Muecke above, there's security reasons that dont allow i to do this:

--You cannot set the value of a file input for security reasons. It can only be set by a user selecting a file in the browser
--If you need to return the view because ModelState is invalid, temporarily save the files, and return their file names so that the user can see what has been already uploaded. This plugin might be of interest

Thanks everyone!

How to get byte array from a file in reactJS

This approach worked for me:

function readFileDataAsBase64(e) {
const file = e.target.files[0];

return new Promise((resolve, reject) => {
const reader = new FileReader();

reader.onload = (event) => {
resolve(event.target.result);
};

reader.onerror = (err) => {
reject(err);
};

reader.readAsDataURL(file);
});
}

You can call reader.readAsBinaryString() if you wish to use binary string. More here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader



Related Topics



Leave a reply



Submit