JavaScript - Axios POST request empty form data (request payload) - javascript

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?

Related

Next JS data fetching with file body

I am trying to send a POST request to upload a file to my IPFS server. However I am unsure how can I upload a file into the body of the request. I have tried looking at the examples from Fetch API, but their example shows files uploaded from a form. While in my case, the files are already within my directory.
Update:
I have revised my code for sending a POST request to my IPFS server based on the documentation on Fetch API and I am now able to successfully send a request. However I am still stuck on how can I get the "fileInput" variable to reference a file from my directory. The current example only works if I have a html form.
I have tried nodejs fs library but I ran into issues where some of the functions are not available. It appears that using fs may pose certain security concerns from what I read. Would appreciate if I can have some advice on this.
var formdata = new FormData();
const fileInput = document.querySelector('input[type="file"]');
formdata.append(
"file",
fileInput.files[0],
`../../ipfs_files/${item._id}.png`
);
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch("http://localhost:5001/api/v0/add", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
you can also send data as base64 string and store it into the database then while accessing convert back to the original format.

HTTP 500 spring web expo image picker

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.

Send file with form-data and axios

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() }

Why is my Giphy API's POST request returning status 400?

I'm trying to upload a gif from the webcam feed to Giphy through their API and it returns status 400 - "Please supply a file upload or a 'source_image_url'". My function does this:
upload = new FormData();
upload.append("file", gif, "usergif.gif");
console.log(upload.get("file"));
fetch("https://upload.giphy.com/v1/gifs?file=" upload + "&api_key=" + apiKey, { method: "POST" })
.then(response => {
console.log(response.status);
return response.json;
}
)
The gif variable inside upload.append() has a value of recorder.getBlob() (I'm using the RecorderRTC API), I also tried to use as a source upload.file and even upload.get("file"), also used URL.createObjectUrl(gif) and changed file= for source_image_url= in the fetch request, even tried to send the gif variable without the use of FormData() but nothing worked.
Do you have a clue?
For those interested, the solution was that when using the POST method, you gotta specify a body header with the file to be uploaded

Reactjs Nodejs file upload ftp via axios

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(....)

Categories

Resources