JS FileReader ArrayBuffer to Byte[] to pass contents of a file - javascript

I have a file upload area in my application, it allows uploads of images, .doc, .docx and pdf.
I need to pass the contents of the file in a byte[] to my api so that it can store the file.
I have tried to convert from ArrayBuffer to Uint8Array but i have not been successful.
Here is my code for reading the file and obtaiing the required information
Any help would be appreciated.
let myFile = ev.target.files[0];
if(myFile.size > 0){
let reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(myFile);
reader.onloadend = (ev) => {
var uintArray = new Uint8Array(reader.result.toString().length);
//var arrayBuffer = new ArrayBuffer(reader.result);
//var array = new Uint8Array(arrayBuffer);
let resourceModel = new AddForumThreadResourceRequestModel({
contentType: myFile.type,
fileName: myFile.name,
fileContent: uintArray
});
console.log(resourceModel);
this.forumApi.AddThreadResource(resourceModel).subscribe(
data => {
if(data != null || data == true){
this.errorCtrl.presentToast("New resource has been added to the thread");
}
});
}

Try to use argument of load event:
reader.onload = (e) => {
var uintArray = new Uint8Array(reader.result);
let resourceModel = new AddForumThreadResourceRequestModel({
contentType: myFile.type,
fileName: myFile.name,
fileContent: uintArray
});
console.log(resourceModel);
this.forumApi.AddThreadResource(resourceModel)
.subscribe( data => {
if(data != null || data == true){
this.errorCtrl.presentToast("New resource has been added to the thread");
}
});

Related

Download file converted from Blob

In Javascript, test browser is Firefox. I have converted files to an array of bytes to store on my server and have used the subsequent code to convert the bytes back to a file, but I am unsure as to how to download the newly created file with appropriate file type can anyone please direct me?
to blob
$('input[type="file"]').change(function(e){
function convertFile(file){
return Array.prototype.map.call(new Uint8Array(file), x => ('00' + x.toString(16)).slice(-2)).join('');
}
file = event.target.files[0];
fileName = file.name;
fileSplit = fileName.split('.');
last = fileSplit.length-1;
let fileType = fileSplit[last];
$('#FileNameVisible').text(fileName);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
fileData = e.target.result;
fileData = convertFile(e.target.result);
console.log(fileData);
};
reader.onerror = function() {
console.log(reader.error);
};
});
from Blob
var file = new File([dataUse], "File", {lastModified: Date.now()});
console.log(file);

Read local file in angular 8

I had a requirement of reading users data from file, the file can be of any format(.csv, .xls, ...)
Users data looks like
Name Email Number Image
Yaswanth yas....#gmail.com 0123456789 file:///home/yash/Desktop/.....jpg
When i reach the image value cells i should pick the image file from local path and convert to base64 but i was not able to read rather i get the following error
Not allowed to load local resource
Later i thought i could have one hidden input file and dynamically set the input value and have onchange even but for security reasons the input type file is read only so dropped my idea and trying with FileReader
Here is the code which i tried
changeListener($event,uploadType) : void {
this.readThis($event.target,uploadType);
}
readThis(inputValue: any,uploadType: any): void {
if(uploadType === 'image') {
}
if(uploadType === 'file') {
var file:File = inputValue.files[0];
this.readThisFile(inputValue);
}
}
readThisFile(inputValue: any): void {
const target: DataTransfer = <DataTransfer>(inputValue);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
this.data = <AOA>(XLSX.utils.sheet_to_json(ws));
console.log(this.data);
this.uploadData(this.data)
};
reader.readAsBinaryString(target.files[0]);
}
uploadData(dataToUpload:any[]) {
var doublemulUserList = []
for (let index = 1; index <= dataToUpload.length; index++) {
this.userObject = {
"Name": "",
"Email": "",
"Number": "",
"Image": ""
};
this.userObject.Name = dataToUpload[index-1]['Name'];
this.userObject.Email = dataToUpload[index-1]['Email']
this.userObject.Number = dataToUpload[index-1]['Number']
var xhr = new XMLHttpRequest();
xhr.open("GET", dataToUpload[index-1]['Image'], true);
xhr.responseType = "blob";
xhr.onload = function (e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res)
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
}
Can some one share some links or an idea on how to go about this problem.

file reader read blob file

i am trying to use filereader to access a blob file located locally, such as c drive, then converts it back to object URL as img src. it is not working, can anyone help this?
never found anyone try to access a blob file from disk. what is the blob file type extension?
const imageOut = document.querySelector('#image-out');
imageOut.addEventListener('load', () => {
const reader = new FileReader();
reader.addEventListener('load', () => {
var f = File.createFromFileName("file:///C:/blob.blb");
const arrayBuffer = reader.readAsArrayBuffer(f);
const blob = new Blob([arrayBuffer], { type: mimeType });
imageOut.src = URL.createObjectURL(blob);
});
});
empty, not show
Check how to use blob here it is clearly explained and it should be enough to get you going.
Try this:
Assuming that file:///C:/blob.blb exists and you are sure, then do it like so:
imageOut.addEventListener('load', () => {
const reader = new FileReader();
var f = File.createFromFileName("file:///C:/blob.blb");
reader.addEventListener('load', (e) => {
const arrayBuffer = reader.readAsArrayBuffer(f);
global.blob = new Blob([arrayBuffer], { type: f.type});
});
// notice this is outside the reader Load.
var intval = setInterval(function(){
if(blob !== undefined){
imageOut.src = URL.createObjectURL(blob);
clearInterval(intval);
}
}, 100);
});
I hope it helps.

Reduce size of image when converted to Base64

I am using the File reader in JavaScript,i need to Post my image to WebApi and convert it into byte Array and save it in server,Its working fine,Now my problem is base64 string increasing the size of image, Let say if i upload image of 30Kb, it is storing has 389Kb in server,How i can save in same size or reduce size of image need help
//File Reader
function OnFileEditImageEntry(file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
var ImageBase64 = evt.target.result;
return ImageBase64 ;
};
reader.readAsDataURL(file);
}
//WEB API//
public IHttpActionResult UpdateUserDetails(ImageModel model)
{
try
{
if (model.ImageBase64 != "")
{
var PicDataUrl = "";
string ftpurl = "ftp://xxx.xxxxx.xxxx/";
var username = "xxx";
var password = "xxxxx";
string UploadDirectory = "xxxx/xx";
string FileName =model.ImageFileName;
String uploadUrl = String.Format("{0}{1}/{2}", ftpurl, UploadDirectory,FileName);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential(username, password);
req.EnableSsl = false;
req.UseBinary = true;
req.UsePassive = true;
byte[] data =Convert.FromBase64String(model.ImageBase64);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
}
}
Send the raw binary instead of increasing the size ~30% with base64/FileReader
with fetch
// sends the raw binary
fetch('http://example.com/upload', {method: 'post', body: file})
// Append the blob/file to a FormData and send it
var fd = new FormData()
fd.append('file', file, file.name)
fetch('http://example.com/upload', {method: 'post', body: fd})
With XHR
// xhr = new ...
// xhr.open(...)
xhr.send(file) // or
xhr.send(fd) // send the FormData
Normally when uploading files, try to avoid sending a json as many developers tends to to wrong. Binary data in json is equal to bad practice (and larger size) eg:
$.post(url, {
name: '',
data: base64
})
Use the FormData#append as much as possible or if you feel like it:
fd.append('json', json)

ParseFile javascript - saved as bytes

I'm trying to save PDF file as ParseFile using Parse javascript SDK:
HTML
<input type="file" id="profilePhotoFileUpload" onchange="selectFile(event)">
JS
function selectFile(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var parseFile = new Parse.File("doc.pdf", file);
parseFile.save().then(function(){
var test = new Parse.Object("TestObject");
test.set("file",parseFile);
test.save();
}, function(error) {
});
}
and i'm getting bytes result as:
http://files.parsetfss.com/637e62db-7116-473c-97dc-48ad15ce73ca/tfss-f5f522d0-0634-4e98-9f2a-be659e5dac00-asdasdas.pdf
any solution?
SOLVED
default file data is Text.
i used FileReader to get data as base64 and then i save data like this:
fr = new FileReader();
fr.onload = receivedText;
fr.readAsDataURL(file);
function receivedText() {
result = fr.result;
var res = result.split("base64,");
var name = "myFile.pdf";
var parseFile = new Parse.File(name, { base64: res[1] });
parseFile.save().then(function() {
console.log("object saved!");
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
}

Categories

Resources