Please help me!
How can I encode file to string base64 in react
handleUploadFile(event) {
let file = event.target.files[0]
// here encoding file base64?
this.setState({
fileData: file,
fileName: file.name
})
}
Here is what you can try out :
handleUploadFile(event) {
let selectedFile = event.target.files;
let file = null;
let fileName = "";
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
let fileToLoad = selectedFile[0];
fileName = fileToLoad.name;
// FileReader function for read the file.
let fileReader = new FileReader();
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
file = fileLoadedEvent.target.result;
// Print data in console
console.log(file);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
this.setState({
fileData: file,
fileName: fileName
})
}
You may need to change it for multiple files though.
Related
I'm trying to build a web server in Rust, and i'm having a few issues trying to upload file into the server. With text based files it uploads fine, but whenever i try to upload other type of media (images, videos, etc), if the file is small enough, it will save, but corrupted, as showned.
original file raw data
file save on the server raw data
And when the file is too big, multer-rs library panicks with "received with incomplete data".
Error log
async fn parse_body(content_type: Option<&String>, body: String) -> HashMap<String, String> {
match content_type {
Some(content_type) => {
let ct = content_type.as_str();
if ct.contains("application/x-www-form-urlencoded") {
let buffer = body.replace("\r\n\r\n", "");
let _body = from_bytes::<Vec<(String, String)>>(buffer.as_bytes()).unwrap();
return _body.into_iter().collect();
}
if ct.contains("multipart/form-data") {
let boundary = multer::parse_boundary(ct).unwrap();
let data = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(body)) });
let mut multipart = multer::Multipart::new(data, boundary);
let mut _body: HashMap<String, String> = HashMap::new();
// Iterate over the fields, use `next_field()` to get the next field.
while let Some(mut field) = multipart.next_field().await.unwrap() {
// Get field name.
let name = field.name().unwrap().to_string();
// Get the field's filename if provided in "Content-Disposition" header.
//
// Process the field data chunks e.g. store them in a file.
while let Some(chunk) = field.chunk().await.unwrap() {
// Do something with field chunk.
if let Some(file_name) = field.file_name() {
let file_dir = format!("src\\static\\temp\\{}", file_name);
let current_dir: &Path = Path::new(&file_dir);
let path = env::current_dir().unwrap().join(current_dir);
if let Ok(mut file) = std::fs::File::create(path) {
file.write_all(&chunk).unwrap();
}
} else {
_body.insert(name.clone(), String::from_utf8(chunk.to_vec()).unwrap());
}
}
}
return _body;
}
},
None => return HashMap::new()
}
HashMap::new()
}
I have an image source , i need to convert it into png file and append it to backend and send. upload is successfull ,but when we retrieve the stored file from backend , it has invalid file format error. I think it was not converted to base64 and because of this we have this issue. I am using $base64 dependency to covert my source.
source = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xjy9Z6xlaXYdts6999ycc3o5p6pXVV3V1Xl6unt62CI5nCFFw6RoyIZtSDIMWTb8wyBk2DBgyYZ/CIT+SJRJGDJNWrboiRRnunu6OR0qp5fq5XRzzjkcY+03ozcoVNebV/eee8639157rbV3Kf/kj35XazbbsFrtqJSa2Ns9Qj5XQa8LOOw+mE0O1Kt9WCxOVCtN5HMlmMx=="
$scope.uploadFile = function(source){
var imageBase64 = $base64.encode(source);
var blob = new Blob([imageBase64], {
type: 'image/png'
});
var filename = Math.random().toString(36).substring(7);
var file = new File([blob], filename + '.png',{type:'image/png'});
$scope.file = file;
var json = {
"json": {
"request":{
"servicetype":"4",
"functiontype": "4012",
"session":{
"sessionid":session
}
}
}
};
fileUpload.uploadFileToEmp( json, file ).then(function(res){
}
}
});
}
I have a function that will determine if the gif is animated or non-animated. Everything is working fine, until i upload those gif to the server, and load it, the blob url is a empty string. How can i generate a blob url for this?
Due to the blob url being empty string, i get parameter 1 is not of type 'blob'
The function below determines if the gif is animated or not.
$scope.isNotAnimatedGIF = function(file) {
var reader = new FileReader();
return new Promise(function(resolve, reject) {
reader.onload = function (e) {
var gifInfo = gify.getInfo(reader.result);
if (gifInfo.images.length <= 1) {
file.animatedGIF = false;
resolve(true);
} else {
file.animatedGIF = true;
resolve(false);
}
}
reader.readAsArrayBuffer(file);
});
}
I am using Angular 1.4.10
Thank you !
You can use URL.createObjectURL() to create Blob url.
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
DEMO
function createbloburl(file, type) {
var blob = new Blob([file], {
type: type || 'application/*'
});
file = window.URL.createObjectURL(blob);
return file;
}
document.querySelector('#file').addEventListener('change', function(e) {
var file = e.currentTarget.files[0];
if (file) {
file = createbloburl(file, file.type);
document.querySelector('iframe').src = file;
//console.log(file)
}
})
<input id="file" type="file">
<iframe src=""></iframe>
try this reader.readAsDataURL(Blob|File).
you can find more from here
I am getting an html file from a backend application and now saving it in pdf format in react. However, unable to open it in adobe :(
CreateFile(data, contentType) {
let file;
if (contentType === "text/html") {
// file = new Blob([data], { type: contentType });
file = new Blob([new Uint8Array(data)], { type: contentType });
}
saveDocument() {
let contentType = "application/pdf";
let file = this.createFile(data,
contentType.toLowerCase());
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // others apart from Safari and Opera mini
var a = document.createElement("a"),
url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
can anyone help?
I suggest you using a library like wkhtmltopdf in your backend to convert the html into pdf before sending it.
I'm working on a app that use cordova-plugin-media to record and audio file, and now I want to encode this file to base64 string, for now I can locate the file but when I try to encode it I get this :
"{"$$state":{"status":0}}"
Here is my code
audio.stopRecord();
audio.play();
if(device.platform == "iOS")
{
var path = cordova.file.tempDirectory;
}
else if(device.platform == "Android")
{
var path = cordova.file.externalRootDirectory;
}
var filename = name + extension;
var filepath = path + filename;
console.log(filepath);
console.log(JSON.stringify($cordovaFile.readAsDataURL(path, filename)));
file path : file:///storage/emulated/0/tPUhcxUKhmLUrWK3Qkqhc69OxeEIWyYrhEB0he9OwM0ffmjY2OUh3TLbFTsApdpIpjxyuC2wouyCs6m7uvdOCHCMiw9mbLMGYM25.mp3
Can any one help me with this??
Thanks
readAsDataURL needs a file object, it won't work with a string path.
Give the following code a try, working on iOS and Android
window.resolveLocalFileSystemURL(path, function(fileEntry) {fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var base64String = evt.target.result;
};
reader.readAsDataURL(file);
});}, function(e){console.log("error:" + JSON.stringify(e));});