unable to upload file from my react application - reactjs

I want to need upload file from react application to backend.
my upload handle function is:
handleupload(info) {
this.setState({ 'selectedFiles': info.fileList });
}
But we are unable to send file data to server.
we are using axios:
export async function saveApplication(applicationData) {
return http.post(
getJobsEndPoint+"/store-application",
applicationData,
{
headers: { "Content-Type": "multipart/form-data" },
}
);
}
But stil unable to get request on my backend controller, we are getting all input type in my backend controller. But still unable to find file object.
Please help me any buddy for regarding same.

Related

File upload issue in Mongoose

I am using Mongoose 6.18 version as an Embedded Web Server for my project. I have an issue when I try to upload a file to the server. I have a react application on the front end that uses axios api with formdata to send the file. ``
await axios.post("http://" + window.location.host + "/upload", data, {
headers: {
"Content-Type": "multipart/form-data",
"Content-Length": ""
}
}).then((response) => {
console.log(response);
console.log(response.data.message);
alert("File Upload successful");
}, (error) => {
console.log(error);
alert("File Upload not successful");
});
On the server side I am using multipart handling as mentioned in this link. I use the function mg_file_upload_handler.
https://cesanta.com/blog/big-upload-example-mongoose-more-than-an-embedded-web-server-2/
By connection closes when the multipart chunks are in progress and every time only a part of file is uploaded. Can someone pls guide me in this.
Please use the latest version instead of an old 6.18, and use of the several upload methods, as described in the tutorial https://mongoose.ws/tutorials/file-uploads/

'Failed to fetch' error when downloading files that has more than 10mb React + Spring boot

Have a client-side server in react that need to request files from backend server (kotlin + spring boot) to download them.
Using the request endpoint in Swagger, Postman and Insomnia, i can success download any file with any size.
In my client-side server, have a list of this files that download can be triggered by a click in an icon. I can download files that has less than 10mb with no error, but when file has more than 10mb, it fails with Failed to fetch error.
Actually, it's a weird behavior. Let say i have a file named FILE A that has under than 10mb and FILE B with 25MB (is the max size allowed to upload). In first entried of the page, if i first request to download FILE B, it throw Failed to fetch. Now, if first request is in FILE A and after FILE B, FILE B download is successed. I'm really confused what is going on here.
Code:
const options = {
method: 'GET',
headers: { "Authorization": `Bearer ${user?.token}` },
};
fetch(`http://localhost:8080/storage/download?fileName=${filePath}`, options)
.then(function (response) {
return response.blob();
})
.then(function (myBlob) {
setSpinControl(false);
const file = new Blob(
[myBlob],
{ type: 'application/pdf' }
);
const fileURL = URL.createObjectURL(file);
if (window) {
window.open(fileURL, '_blank');
}
})
.catch((err) => {
setSpinControl(false);
console.log(err)
});
Already tried some alternatives:
Using axios (throw Network Error);
Using libraries as file-saver;
Setting timeout to 9999999;
All achieve same behavior.
I read too that createObjectURL uses memory to perform download, but max size of a file is validated to be 25MB.
Some print of Network tab:
Request Header:
Request Response:
Network List:
Any tips what i can do here?

send file from formik reactjs to springboot using axios with saga

i can send file "userPicture" from postman and get it in the backend (springboot )and i save it to my database mongodb without any problem
but when i send the picture from the form i use Formik component in reactjs and axios
i display the content of my input userPicture i get
in axios i made this to sent the request. for boundary i dont know what is i made copy past "WebKitFormBoundaryQ0pBuvRC1EzDAQWT" from an exemple
try {
const { user } = action;
console.log(user);
const request = yield axios({
method: 'post',
url: ENDPOINTS.USER + '/add',
data: user,
headers: { 'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryQ0pBuvRC1EzDAQWT----' }
});
in the backend i get this error
,org.springframework.validation.BindingResult,org.springframework.web.multipart.MultipartFile,org.springframework.web.multipart.MultipartFile)
throws java.io.IOException: Required request part
'userPicture' is not present
i get the same error in postman when i send request without userPicture parameter
Looks like you sending the file incorrectly. If you want to send multipart/form-data from client to server, you need to use FormData.
Like this
const formData = new FormData();
formData.append('usePicture', user)

React Axios Appends Window Origin To Provided Url (json-server)

I have a weird behaviour while integrating a json-server api with axios.
I use json-server to serve a db.json file
json-server --watch db.json --port 4000
and in my react application I use axios to call "http://localhost:4000/tasks"
Testing it on postman, the API returns results and it is working fine.
but using the code snippet below (axios) it concatenates both domains of the react app and the api Url to the request.
try {
return axios({
method: 'GET',
url: `http://localhost:4000/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
I check in the browser network and I the request Url like that
Request URL: http://localhost:3000/http//localhost:4000/tasks
and therefore throws a not found - 404 exception
Any idea why is this happening?
The weird thing is that When I use another API like star wars api "https://swapi.co/api/people/1", It works like a charm.
Thanks in advance...
I've fixed this problem by using environment variables.
I just created a ".env.development" file and added "REACT_APP_API_BASEURL = 'http://localhost:4000'".
And then I used it as follows:
try {
return axios({
method: 'GET',
url: `${process.env.REACT_APP_API_BASEURL}/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
and it worked perfectly.
Just faced this issue, it's because the url used in axios is wrong. In this case, the url in the original question is
http://localhost:3000/http//localhost:4000/tasks
Notice http//localhost:4000/tasks this is missing a colon after http. Fixing the url will fix this issue in case someone else is facing this again

React upload a file to spring controller

We have a Java spring-boot based server and a react JS UI app.
And we need to implement a file upload from the react app to the server.
Server controller code:
#RequestMapping(value = "/aaa/{id}/upload", method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Object uploadFile(#PathVariable("id") Integer id, #RequestParam("file") MultipartFile file, HttpServletRequest request) {
...
logic
...
}
With postman, we can upload the file successfully. We can't do it via the react JS app.
This is react JS upload file code:
uploadFile(file, type) {
const formData = new FormData();
formData.append('file', file);
return axios.put(`aaa/1/upload`, file, {
headers: {
'content-type': 'multipart/mixed; boundary=--ABC123Boundary'
}
})
.then(() => {
NotificationsManager.info('File successfully uploaded.')
})
.catch((err) => {
NotificationsManager.error(err.message, `Error in uploading file`);
});
}
We tried with boundary, without boundary, with default boundary... nothing works.
UPDATE: We get this error:
"Bad Request"
exception:
"org.springframework.web.multipart.support.MissingServletRequestPartException"
message:"Required request part 'file' is not present"
What did we do wrong?
Regards,
Ido

Resources