I am trying to upload a file in react native using axios to a spring service backend.
const sf5 = async () => {
let fd = new FormData();
fd.append("file", imgimg.uri)
const eeefile = await instance.post('/uploadfile', {
body: fd
}, {headers:{
"Content-Type": "multipart/form-data"
}}).then(function (response) {
//console.log('~~~~~~~~~~~~~~~' + random_val)
//console.log(response);
});
}
However, spring framework is rejecting the request saying
[dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request]
I tried placing a breakpoint in the spring application class. However, request didnt even reach there.
The am able to upload the file from browser through XHR.
Any pointers would be appreciated.
Related
I am using laravel application with Vuejs so I want after a certain process is completed to save the information by hitting the post method endpoint.
In the local environment, it's working perfectly but after I launch the application on Cpanel I am getting this error.
So please someone may help me to figure it out thanks.
let formData = new FormData();
formData.append("series_id", this.series.id);
formData.append("user_id", this.users);
formData.append("transaction_id", response.data.params.transactionId);
formData.append("request_id", response.data.requestId);
formData.append("amount", response.data.params.txAmount);
let url = "https://example.so/api/add-purchase";
axios.post(url, formData, headers).then((response) => {
console.log(response);
if (response.status == 200) {
alert(response.data.message);
window.location.href ="/student/courses";
}
});
this.isLoading = false;
I want to send an array of objects inside formdata in React JS. When I am appending data inside formdata, it is being received as null at the backend and the API is returning me 500 internal server error. I have tried some of the solutions from the internet but not much support was found. The ways that I have tried till yet are mentioned below:
const surveyFormAnswers = [{Answer: "Hello", QuestionId: 1}, {Answer: "Document", QuestionId: 2, File: file (object)];
const data = new FormData();
data.append('SurveyFormAnswersDtos', JSON.stringify(surveyFormAnswers));
await executeAddSurveyFormAnswers({data: data});
In this case, I am sending a stringified array at the backend (I can see my array being sent inside the browser's Network tab), but at backend, we are using dotnet core5.0. We do not know how exactly can we deseriliaze or parse our request data.
In the second approach, I am appending my data manually inside the formdata (got this approach from the internet) but this is also sending me 500 internal server error from the backend. My code in this case looks like below:
const data = new FormData();
for (var i = 0, valuePair; (valuePair = surveyFormAnswers[i]); i++)
for (var j in valuePair) data.append(j, valuePair[j]);
await executeAddSurveyFormAnswers({data: data});
I am also attaching a postman screenshot so that you can check the required format of data to be sent
Click on the link below to see data being sent using postman
I have been using customized hook for axios and the definition for AddSurveyFormAnswers is below:
export function AddSurveyFormAnswersUrl(token) {
return {
url: `/SurveyAnswer/AddSurveyAnswers`,
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
ContentType:
"multipart/form-data; boundary=<calculated when request is sent>",
},
};
}
I have a Vue.js app which uses axios to interact with a Laravel API. I'm trying to make a POST request with an image file in it to upload in the backend.
The issue I'm having is that axios makes the POST request with empty payload.
I've tried sending it both as a plain JS object and with FormData. In both cases the request payload is empty. I've looked on the internet for hours but I was unable to find anything while trying to tackle the issue in the past few days...
This is how I make the request:
let fd = new FormData();
fd.append('file', this.file);
console.log(...fd) //shows the file is there with its data
axios
.post("/api/images", fd)
.then(response => {
//Handle success
})
.catch(errors => {
//Catch errors
});
This is how I get the file from the form:
let selectedImage = this.$refs.fileInput.files[0];
const reader = new FileReader();
reader.addEventListener('load', (event) => {
this.file = event.target.result;
});
reader.readAsDataURL(selectedImage);
I've tried experimenting with the request headers and at the moment they are as follows:
"Accept" : "application/json",
"Content-Type": "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2),
"Authorization": "Bearer " + this.user.api_token,
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content
The responses from Laravel are always that the file is required (as expected when it's indeed missing).
I did try encoding the file in Base64 but I have trouble validating that it's an image in the backend.
I found this similar question but it wasn't of any help: FormData sends empty data using axios
I want to send a file + JSON data but I'm ok with just making the file upload work. So... How do I send a file from Vue.js app to Laravel API using Axios? What am I doing wrong?
I am trying to send a video to a videosite, I am able to upload the video using the REST api and postman, so I know the api works as intended. Now I want to do exatcly the same request using axios. I have code that looks like the example on how to use form-data and axios:
const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);
form.append('image', stream);
// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();
axios.post('http://example.com', form, {
headers: {
...formHeaders,
},
})
.then(response => response)
.catch(error => error)
I get the error that data: 'Content-Length is required'
Any ideas?
May be I got your questions wrong , you want to add Content-Length in the header.
I can see you are uploading video stream. So first you have to calculate the data chunk length.
('Content-Length', File.getSize(stream))
Reference: Can I stream a file upload to S3 without a content-length header?
You can make the post request as multi-part type : 'Content-Type': 'multipart/form-data'.
It is preferable way to send large data to server.
You can check this link : How do I set multipart in axios with react?
If I got your question wrong , plese comment or reply . Thanks
The solution to my problem was to set Content-Length accordingly:
"Content-Length": fs.statSync(filePath)['size']
I think the best way to handle this is to actually use the FormData's own method:
const headers = { 'content-length': formData.getLengthSync(), ...formData.getHeaders() }
This will be more accurate because it includes any other data you may add.
To expound, if you are using a ReadStream, you must use the async function instead.
const { promisify } = require('util')
const getLength = promisify(formData.getLength.bind(formData))
const contentLength = await getLength()
const headers = { 'content-length': contentLength, ...formData.getHeaders() }
I am trying to upload file using React Dropzone on ftp with Reactjs + AXIOS at front end, Nodejs + connect-multiparty at back end.
The problem is when I am sending file via front end using AXIOS, I am not getting the file at server in request.
My code to upload file using react-axios is
let data = new FormData()
data.append('file', file)
var setting = {
method: 'post',
url: 'my-server-url',
data:data,
headers: {
'Content-Type': 'multipart/form-data'
},
}
var response = axios(setting).then(response => { return response.data })
.catch(response => response = {
success: 500,
message: "Your submission could not be completed. Please Try Again!",
data: ""
});
while using postman, everything works fine. Server side api is working. only problem with client side request code.
Any help!!!
This is a very rookie mistake you're making probably because of the fact that you don't understand the way multipart works. For your client-side code to work, i.e form-data to be sent back to the backend, you need to:
Either remove the header and let the browser choose the header for you based on your data type
Or when using 'Content-Type': 'multipart/form-data', add a boundary to it
Multipart boundary looks like this,
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryABCDEFGHIJKLMNOPQRSTUVWXYZ'
Simply doing the following will solve the issue for you as the browser will take care of the headers needed.
axios.post('your-server-url', data).then(....)