How to upload image or file in react js? - reactjs

I want to upload image / file in a react project, but dont want to use formdata to post, instead i want to use body for the post method through Axios.
If I can convert my file into base 64, I think i will be able to post the image through body.
Can anyone tell me solution how to achieve this?

Use this code :
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}

Related

How to save SURVEY PDF on the disk

I want to save somes PDF created with 'survey-pdf' on my disk.
Actually, i can send the PDF but i can't save it on my disk.
My final code :
return surveyPDF.save(filename);
Someone can help me ?
Thank you
Can you try
await surveyPDF.save(filename)
?
.save seems to be an asynchronous function that downloads the PDF file.
From the docs
Call save method of surveyPDF object to download file in browser. This is asynchronous method
#2 If the first method doesn't work, you can try this
function savePdfAsString() {
const surveyPDF = new SurveyPDF.SurveyPDF(json);
surveyPDF.data = survey.data;
surveyPDF
.raw("dataurlstring")
.then(function (text) {
//var file = new Blob([text], {type: "application/pdf"});
var a = document.createElement("a");
//a.href = URL.createObjectURL(file);
a.href = text;
a.download = "surveyAsString.pdf";
//document
// .body
// .appendChild(a);
a.click();
});
}
Here you are using the .raw function to transform the PDF into a dataurlstring and then downloading that. Here's the docs for this
*Not tested

axios.post correct path param

Super newbie to ASP.NET Core with React,
and try to build "upload file" functions.
From my react component,
I have input as follows, and trigger UploadFile function
<input type="file" onChange={(event) => UploadFile(event)} />
and in UploadFile function, it looks like this
function UploadFile(e) {
var file = e.target.files[0];
var formData = new FormData();
formData.append("file", file);
axios.post("/FileUpload/SingleFile", formData);
}
and the controller for SingleFile looks like this
public IActionResult SingleFile(IFormFile file)
{
using (var fileStream = new FileStream(Path.Combine(_dir, "file.png"), FileMode.Create, FileAccess.Write))
{
file.CopyTo(fileStream);
}
return RedirectToAction("Index");
}
But having a bit tricky time to figure out what is the right url path to pass on to the
axios.post(???, formData).
Is the path should be
"/'controller name'/'IActionResult method name'"??
With the current path, I get an 404 error which means wrong path.
Help!
The path I had was correct,
but the problem was that I was using ASP.NET Core 3.0
so I need to generate the antiforgery token.
The answer is listed here
Enable Antiforgery Token with ASP.NET Core and JQuery

React Native File-Conversion

I'm trying to convert an audio file into a Base64String to upload to a server.
For certain reasons, I want to do this on the phone before I upload this. I'm using React Native inside the Expo kit.
My file structure looks like this:
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('file', {
uri,
name: `file.${fileType}`,
type: `audio/${fileType}`,
});
Assume we have the uri and it's a .wav audio file
I was able to do this conversion with a NodeJS server with multer doing the heavy lifting.
It would give a buffer to the route and then I could convert the buffer to a base64 string and then send it to another server to process the buffer.
Any idea how can get this done on React Native or purely on the frontend?
Thanks!
You can use FileReader class.
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
Or you can send as a blob (It is not base64).
Use https://github.com/wkh237/react-native-fetch-blob library

Is there an alternative for File() constructor for Safari and IE?

I am using the File() constructor for creating file object for uploading a blob file to the server. The following code works fine for Chrome, but fails for Safari and Internet Explorer.
image_url = new File([blob],file_name,{type: mimeString});
The code is breaking at this line and getting this error in console "FileConstructor is not a constructor" (evaluating 'new File([blob],file_name,{type: mimeString})')
Using the FileReader API is an alternative to this but I am not able to fix this issue.
I Suggest to use the blob api, I've found the same problem and I solved like that:
var html = <svg>whatever on svg </svg>
var fileName = "myfile.svg";
var blob = new Blob([html], {type: 'image/svg'});
blob.lastModifiedDate = new Date();
// var blobAttrs = {type: "image/svg"};
// var file = new File([html], fileName, blobAttrs);
var formData = new FormData();
formData.append("file",blob,fileName);
It is not a "file", but you can use it like it was.
According to web "Can I use" Safari does not support the new File() constructor. See this link http://caniuse.com/#feat=fileapi
So I think you have to either use FileReader or maybe use some of the polyfills listed here https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills
Especially this one could be useful for you https://github.com/mailru/FileAPI (I did not use it myself)
Also have a look at this SO answer What to use instead of FileReader for Safari?
If you can use ES6 classes:
class CustomFile extends Blob
{
constructor(blobParts, filename, options) {
super(blobParts, options);
this.name = filename || "";
if(options) {
this.lastModified = options.lastModified;
}
}
lastModified = 0;
name = "";
}
const blob = new Blob();
const fileObject = new CustomFile([blob],"myfile");
console.log(fileObject);
There is a File ponyfill on npm which works with modern module imports. This makes usage simple but you do need to import it in every module where you use new File().
import File from '#tanker/file-ponyfill';
const myFile = new File(['somefiledata'], 'example.txt', { type: 'text/plain'});

saving the cropped image - to amazon s3

I am cropping the image . But When I upload it to the amazon , it saves the originalfile.
function _handleFileSelect(evt) {
$scope.beforeLogoSelect = false;
$scope.file = evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function(evt) {
$scope.$apply(function($scope) {
$scope.myImage = evt.target.result;
});
};
reader.readAsDataURL($scope.file);
}
This way I get the url of the image and assign it to the cropped image tag.
Now How shal i save the cropped file to a file variable so that I can upload to amazon s3? I want the resultant cropped image in $scope.file.
Thanks.
Converting the data uri to blob was the solution.
Convert Data URI to File then append to FormData
Might be useful for others.

Resources