Transform img from url to file in React - reactjs

I have an autocomplete section that searches movies through MovieDB api.
The result of the api has a field called poster_path that contains the path where the image exists.
"poster_path": "/lRQiJXETkCnVVurHmglNvMXrZOx.jpg"
I have a react project for front-end and a spring boot project for backend.
The thing I want to do is to get the image convert it to file and the send it to the backend controller as a multipart file.
How can I convert the image from url to file in React?
I've tried this but re.data returns the byte array I think:
axios.get(e.image).then(re => {
setFile(re.data)
});
And here is the controller:
public ResponseEntity<Post> post(#RequestPart(required = false) MultipartFile file, #RequestPart #Valid PostResource postResource, Principal principal)

Related

Download file from api in ReactJs

I have ASP.NET Core MVC back-end api. One controller returns File from server. Is there a way to make request to api route by [href] attribute of <a> tag? Looks like it tries to call React route but not make a request to server.
Also I made AJAX call to that controller and got back file as a string (screenshot is attached). Why is it a string, shouldn.t it be a byte array? How to build back file from that string? (it's a .pdf file). I have an empty PDF if use JavaScript new File([], 'name', {options}).
ASP.NET Core controller returns PDF this way:
return PhysicalFile(Path.GetFullPath(relativePath), "application/pdf", reportName);
In React I receive it as a string this way:
let stringPDFBinary = await ReportService.getReport(id, reportFileName)
I just need to download file from api by any way.
So, the answer is here: PDF is blank when downloading using javascript
The same problem. Let it be one more topic, easier to find for others. The AJAX response is encoded string. In request config set 'responseType = 'arraybuffer'' somehow and receiving pdf will not be blank. Solved.
I Just copied and pasted from the code source. The problem seems to be the same that i had:
Asp net controller:
[HttpGet]
[Route("File")]
[AllowAnonymous]
public IActionResult GetFile(string key)
{
var file = (FileCacheValue)_fileCache.Cache[key.Replace(" ", "+")];
if (file == null)
return NotFound();
Response.Headers["content-disposition"] = $"inline;filename={file.Name}.pdf";
return File(file.Data, "application/pdf");
}
In this case comes from a cache system. The data is a byte array.
Front-end React:
const onClick = () =>
{
window.open(pdfByteArray, '_blank', 'fullscreen=yes');
}
Exactly what i have. I just put the data on a new window and open the pdf.
The Ajax part is straight forward, get the value from the response and set it on a variable

How to get an image from firebase storage using the GUI of firebase?

So I uploaded an image to the firebase storage and I refference it in a user collection like that:
displayname: "David"
avatar: gs:/news-14b77.appspot.com/avatar Images/david.jpg
now I want to get that object in my project (React) and to view that image, the object i get when i console log it is that:
displayname: David,
avatar: n,
how do I get the image there?
The gs:/news-14b77.appspot.com/avatar Images/david.jpg is a URL type that is only usable with the Firebase Storage and Cloud Storage SDKs. You can't directly add it to an img view, as that won't know what to do with the gs:/ protocol.
So you'll need to use the Firebase SDK to convert the gs:/ URL to a so-called download URL, which is a URL that gives public read-only access to the file. That's be something like:
var ref = firebase.storage().refFromURL('gs:/news-14b77.appspot.com/avatar Images/david.jpg');
ref.getDownloadURL().then((url) => {
// in here you can set the URL for the avatar
});
Or (using await):
let ref = firebase.storage().refFromURL('gs:/news-14b77.appspot.com/avatar Images/david.jpg');
let url = await ref.getDownloadURL();
// here you can set the URL for the avatar
For more examples of this, see the Firebase documentation on getting data via a url.

React / Rails API Image Uploading

I've built a React frontend along with a Rails API only backend. I want to allow the user to create a task and enter a title, description and upload an image.
So I've attempted to use DropZone to get access to the image and then send the image info along with the title and description to my Rails API via a post request using Axios.
I set up Carrierwave on my Rails API in hopes of uploading to an AWS S3 bucket once my Task has been added to the database per the post request.
None of this is working so my question is, should I take care of the image uploading to AWS on the react side and if so, how do I associate that image with the additional information I'm saving to my Rails database (title and description).
Thanks!
First, on React side, there should be no proble with title and description, but for image, you need to encode the image to Base64 string. It is something like this.
getBase64 = (callback) => {
const fileReader = new FileReader();
fileReader.onload = () => {
console.log(fileReader.result);
};
fileReader.readAsDataURL(fileToLoad);
fileReader.onerror = (error) => {
console.log('Error :', error);
};
}
Then, on Axios, send those 3 parameters alltogether with one POST request.
For Rails, you need to set up code that can read the Base64 string. Usually, you can use Paperclip or CarrierWavegem to add image attachment. It will look like this.
property_image = listing.property_images.new(param_image)
if param_image[:file_data]
image_file = Paperclip.io_adapters.for(param_image[:file_data])
image_file.original_filename = param_image[:image_file_name]
image_file.content_type = "image/png"
property_image.image = image_file
end
private
def param_image
params.permit(:image, :image_file_name, :file_data)
end

Angular file upload custom http post files

I am using nervgh/angular-file-upload to upload files. As I know, this angular-file-upload has their own upload functions.
Currently I need only the files inside the uploader, and then I will use my custom http post
$scope.UploadUserFiles = function () {
$scope.UserFileRequest = {"File": uploader, "User": myUser}
$http.post(host + "/api/user", $scope.UserFileRequest).then(function (response) { });
}
Currently I am having the trouble of getting those files from the uploader since I have no idea about the properties and structure. But for User is my own class at the web api, so I have no problem to get any info that I want.
The main problem is I have no idea how to catch/initialize the uploader it into a variable after post to my web api.
[HttpPost]
[Route("api/user")]
public UserFileResponse GetUserFile(UserFileRequest userFileRequest)
{
//What should I do to get the Files from the request and save into the server?
}
My UserFileRequest contain the info of myUser, but I do not know what to do with the uploader since I do not have a class to hold it.
From what I understand in your question, you are having trouble getting the files in the queue into your own file upload function.
The functions within the FileUploader class have callbacks that you can use, but another way to easily expose the file queue would be to create your own callback once the 'upload' button is clicked.
someFxn(item) {
console.log(item);
_someUploadFxn(item)
}
<md-button class="md-blue" ng-click="$ctrl.someFxn(item)" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
Upload
</md-button>
This will allow you to view the file that has been queued up and from there you can pass it or whatever properties you need off that file object into your own uploader function.
The same goes for if you are wanting to upload a bunch of files at once.

Swagger UI how to display upload of multiple files

I've a Spring MVC application that is wrapped with Swagger annotations.
<spring.version>4.1.8.RELEASE</spring.version>
<java-version>1.7</java-version>
<springfox-version>2.1.2</springfox-version>
I've a controller with two resource endpoints to allow file upload - one endpoint for a single file upload and other with multiple file upload.
Single file upload -->
public #ResponseBody UploadAPIResponse postInboundFile(
#ApiParam(value = "file to upload") #RequestParam("file") MultipartFile file,
#ApiParam(value = "Inbound trigger flag ") #RequestParam("triggerInbound") Boolean triggerInbound)
throws SQLException, Exception {
Multi file upload -->
public #ResponseBody BulkUploadAPIResponse postInboundFilesAsync(
#ApiParam(value = "files to upload") #RequestParam("files") MultipartFile[] files,
#ApiParam(value = "Inbound trigger flag ") #RequestParam("triggerInbound") Boolean triggerInbound,
HttpServletRequest request) throws SQLException, Exception {
On viewing the Swagger UI for the api documentation,
I see that for single file upload API, against the "file" parameter, I get a file upload button.
However for the multi file upload API, I get the "files" parameter as a text box.
Can someone pls help me how can I get a file upload button against the "files" parameter of multi-files upload API and I'm able to upload multiple files as part of single request ?
I've gone through various other posts on this context but not able to find a concrete approach to address this issue.
PS : I've the understanding that naming the parameter as "file" provides the file upload button automatically through Swagger-UI. I tried to use the parameter name as "file" instead of "files" for the multi-file upload API but that didn't help; i still end up getting a text box (probably reason being that argument is an array of MultipartFile).
Thanks in advance for any pointers/suggestions.

Resources