Can't find variable: file with axios image uploading - reactjs

I read that axios is good for image uploading to the database and here is what I got so far:
var photo = {
uri: this.state.userimgSource,
type: this.state.userimgSourceType,
name: file, <-- here
fileName: Image.png
};
var body = new FormData();
body.append('file', photo);
axios({
method: 'post',
url: `https://www.example.com/React/user-image-upload.php`,
data: body,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
I am new to Axios and I am not sure why I am getting Can't find variable: file. I tried to put file into a string and react native will not accept that. If file needs to be a variable, what would I define it with?

Related

React - Download image from url without saving it to filesystem and send it to Node Api

We have requirement where we have to read 1-10000 image URL from one location. Sample array
[
{
"asin": "B00HZ9Q8XM",
"image": "https://m.media-amazon.com/images/I/41gKlxTYnkL._SL500_.jpg"
},
{
"asin": "B00JOW20TY",
"image": "https://m.media-amazon.com/images/I/511Ae304D5L._SL500_.jpg"
}
]
We need to loop through above array, download or read image, call an external node api which will accept image as file with multipart/form-data and file type can only be jpg
We wanted to do this without saving files on local server as there will be 100 of such request and don't want to fill up server space.
What we tried so far, we can download image as blob or arrayBuffer like following;
export const downloadImageFromUrl = async(url) => {
// const response = await fetch({
// url,
// method: 'GET',
// responseType: 'stream'
// });
const response = await axios({
url,
method: 'GET',
responseType: 'blob'
});
console.log('response ', response)
//fs.writeFileSync('./temp.jpg', res.data);
return response;
}
But when we send it to node api, it says filetype is blob and reject our request. Can you please advise best approach to achieve this ?
Just use the arraybuffer response type.
P.S. Blobs are not currently supported by Axios on the Node.js platform;
const response = await axios({
url,
method: 'GET',
responseType: 'arraybuffer'
});

Bad request status 400 when trying to upload image file to imgur

I'm trying upload image file from my React app.
Keep getting 400 error, witch I can't understand why.
That's my TypeScript function's code in React:
public setImage = (args: ChangeEvent<HTMLInputElement>) => {
const image = args.target.files[0];
let formData: FormData = new FormData();
formData.append("profileImage", image, image.name);
const requestOptions = {
method: 'POST',
headers: { 'Authorization': 'Client-ID //my client-id here//' },
image: image
};
fetch('https://api.imgur.com/3/image', requestOptions)
.then(response => response.json())
.then(data => console.log(data));
}
And the error:
{
data: error: "No image data was sent to the upload api"
method: "POST"request: "/3/image"
__proto__: Objectstatus: 400
success: false
__proto__: Object
}
When i'm trying to console my FormData object after appending I can see an empty object.
Thanks for any answer!
The first thing that comes to mind is to log the image object as well and see if there are any problems there.
Also please take a look at this to verify that you're logging your FormData object correctly.
If however, this is still not enough to debug the issue, I would advise you to try rolling a request using something like curl or Fiddler since you are manually creating the POST headers. Because of this, you're not sending the Content-Length header which could cause the imgur api to just skip the whole body of your request.
To get the content lenght you could do something like:
let content-length = JSON.stringify(formData).length;
Then simply:
const requestOptions = {
method: 'POST',
headers: { 'Authorization': 'Client-ID //my client-id here//', 'Content-Length': content-length },
image: image
};
Hope this is useful in some way.

File Upload using spring rest and axios, no multipart boundary was found

I have some issues in file uploading using spring rest and react and axios,
my back-end code is
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity uploadFile(#RequestParam MultipartFile file) {
return ResponseEntity.ok().build();
}
and I can upload file using postman, but by using axios I got some errors.
nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
here is my code:
let formData = new FormData();
formData.append("file", this.state.selectedFile);
axios({
method: "post",
url: url,
data: {
formData
}
})
also if I put
headers: { "Content-Type": "multipart/form-data" }
I got error too,
can anyone tell me what are my mistakes please?
It may be beacause you are creating a new object and sending the data inside the object
Try this data: formData
let formData = new FormData();
formData.append("file", this.state.selectedFile);
axios({
method: "post",
url: url,
data: { formData},
{...axios.default.headers,
...{headers: { "Content-Type": "multipart/form-data" }}
}
})
You dont need to put any headers as it will automatically , decides the parameters of headers , when you do it manually you need to explicitly decides few parameters which is quite difficult to judge , so dont give headers

axios POST request to strapi image upload [Internal Server Error]

I'm uploading an image to strapi using axios but the response is 500 error. However in Postman the request is 200
POSTMAN
AXIOS CODE
let bodyFormData = new FormData();
bodyFormData.append('files', this.state.avatar, this.state.avatar.name)
bodyFormData.append('ref', 'user')
bodyFormData.append('refId', getId())
bodyFormData.append('field', 'avatar')
bodyFormData.append('source', 'users-permmissions')
axios({
method: 'post',
url: `${strapi}/upload`,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${withToken()}`,
},
data: bodyFormData,
}).then(res=>console.log(res.data)).catch(err=>{console.log(err.response.data.message)})
what's supposed to be the issue here?
Here's part of the strapi user model
{
"avatar": {
"model": "file",
"via": "related",
"plugin": "upload",
"required": false
}
}
The solution is to throw Axios in the trash. I struggled with this for a day of my life that I will never get back. There's a longish, years-old thread at https://github.com/axios/axios/issues/318 with people complaining about being unable to get multipart form uploads to work with Axios.
I switched to the request-promise module and got it to work within minutes, using the following simple code:
const fs = require("fs-extra");
const rp = require('request-promise');
let out = await rp({
method: 'POST',
uri: 'http://mystrapihost/upload',
formData: {
// Like <input type="text" name="ref">
'ref': "customer", // name of the Strapi data type, singular
'field': "attachments", // a field named "attachments" of type "Media"
'refId': "838e238949ewhd82e8938299e289e99", // strapi ID of object to attach to
// Like <input type="file" name="files">
"files": { // must be called "files" to be "seen" by Strapi Upload module
name: "myfile.pdf",
value: fs.createReadStream("/path/to/myfile.pdf"),
options: {
filename: "myfile.pdf",
contentType: 'application/pdf'
},
},
},
headers: {Authorization: 'Bearer myjwtgobbledygook123456'} // put your JWT code here
});
console.log(out);
Enjoy!!

Uploading an image with multer / react-dropzone

I cannot seem to upload an image to my uploads folder using express,multer and react-dropzone. My code is as follows:
<Dropzone
style={{position: "relative"}}
accept="image/*, video/*"
onDrop={this.onDrop.bind(this)}
onDragEnter={this.onDragEnter.bind(this)}
onDragLeave={this.onDragLeave.bind(this)}
name='avatar'
>
{ dropzoneActive && <div style={overlayStyle}>Drop files...</div> }
<div>
<h2>Dropped files</h2>
{
files.map(f => <div><li>{f.name} - {f.size} bytes</li>
<img style={{height:'100px'}}src={f.preview}/></div>)
}
</div>
</Dropzone>
A basic file upload using the dropzone example. Then my submit function is:
createBlog(){
var file = this.state.files[0];
var file_name = file.name;
//api/blog
fetch('http://localhost:8080/saveBlog', {
method: 'POST',
headers: {
"Accept": 'application/json',
'Content-Type': 'application/json',
//"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({
file: file,
file_name: file_name
})
}).then((response) => {
...
}))
}, function(error) {
console.log('error: ',error.message)
})
}
Note that file returns all the properties that image has, E.G. lastModifiedDate, name, preview, size, type, webkitRelativePath.
However, when I pass the data to the server the response I get is :
{ file:
{ preview: 'blob:http://localhost:3000/954e0002-3045-44c4-bcd8-70dc26d0d416'
},
file_name: 'image.jpg' } 'Body'
undefined 'files'
Where my server code involving the image is :
var multer = require('multer');
var upload = multer({ dest: './uploads/' });
...
...
router.post('/saveBlog', upload.single('avatar'), function(req, res, next) {
console.log(req.body, 'Body');
console.log(req.file, 'files');
res.end();
});
I am hoping someone can help tell me why my images are not going to my uploads folder as I have spent a long time trying to figure out this basic example.
Your issue is that you're trying using JSON.stringify() for your request payload and Multer expects and only works with formData. You also need to remove the headers you have or use 'content-type': 'multipart/form-data'
You have:
body: JSON.stringify({
file: file,
file_name: file_name
})
You need to use formData() instead:
createBlog(){
const file = this.state.files[0];
const file_name = file.name;
let data = new FormData();
data.append('file', file);
data.append('file_name', file_name);
fetch('http://localhost:8080/saveBlog', {
method: 'POST',
body: data
}).then((response) => {
...
}))
}, function(error) {
console.log('error: ',error.message)
})
}

Resources