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)
})
}
Related
I am trying to upload a file to the server and the server APIs are written using django. The file upload is working perfectly from Postman but when i try to upload from mobile app (React Native) using axios the backend is not able to read it.
Following is the Frontend Snippet:
let accessToken = await AsyncStorage.getItem('accessToken')
let formData = new FormData()
formData.append('doc_type', this.state.selectedDoc.id)
formData.append('document', this.state.selectedFiles) // <- This is the fetched file in array format . [{filname:'abc', size:12344,.....}]
formData.append('description', this.state.description.value)
formData.append('data', JSON.stringify(this.state.selectedDoc.fields))
let url = `${AppConstants.url}api/${AppConstants.apiVersion}/upload_doc`
var config = {
method: 'post',
url: url,
data: formData,
headers: {
'Authorization': `Bearer ${accessToken}`,
}
}
axios(config)
.then((resp) => {
resolve(resp)
})
.catch((err) => {
reject(err)
});
And the backend-end if else statement is as follows:
if(request.FILES.getlist("document")):
files = request.FILES.getlist("document")
....
....
....
else:
return response.JsonResponse({
'success' : False,
'message' : 'Please Upload a file'
}, status = status.HTTP_200_OK)
The above else block is executed even though the UI is sending a valid file.
Request you to please share a solution.
We are building an application that uses React framework for the frontend and Laravel framework for the backend. The problem is whenever sending a post request for '/store-image' route. The response returns with Error 500: Call to a member function storeAs() on null.
It seems that Laravel isn't reading the request.
Here is my request code:
const formDa = new FormData();
setSelectedFile(imgRef.current.files[0]);
formDa.append("file", selectedFile);
fetch("https://api.pharo-tech.xyz/store-image",{
method:'POST',
body : {
image : formDa,
},
headers : {
'Authorization': 'Bearer ' + token,
'Accept' : 'application/json',
'Content-Type' : 'multipart/form-data'
}
}).then(res=>res.json()).then(data=> console.log(data)).catch(e => console.log(e))
Here is my ImageController.php code:
public function store(Request $request) {
$request->file('image')->storeAs('profile_images', mt_rand(100, 1000000000) . ".{$request->file('image')->guessExtension()}");
}
You append formDa.append("file", selectedFile);and from API you try to get file $request->file('image'). Here your attach file stored in file not image.
You need to update your code as below.
HTML
<input type="file" onchange="onLoadImage(this)">
Script
function onLoadImage(e) {
var token = '';
var selectedFile = e.files[0];
const formDa = new FormData();
formDa.append("image", selectedFile);
fetch("https://api.pharo-tech.xyz/store-image", {
method: 'POST',
body: formDa,
headers: {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
}
}).then(res => res.json()).then(data =>
console.log(data)).catch(e => console.log(e))
}
API
public function store(Request $request) {
$request->file('image')->storeAs('profile_images', mt_rand(100, 1000000000) . ".{$request->file('image')->guessExtension()}");
return response()->json([success: true]);
}
I've written the following script:
function uploadImageToDiscord() {
var link = "https://i.imgur.com/image.jpg";
var img = UrlFetchApp.fetch(link).getBlob();
var discordUrl = "https://discordapp.com/api/webhooks/mywebhook";
var payload = {
"file": img
};
var params = {
headers: {
"Content-Type": "multipart/form-data"
},
method: "post",
payload: payload,
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
However, GAS tells me that I'm trying to send an empty message. Can anyone help me?
Error Message
The error must be related to either the way of me trying to download the image:
var img = UrlFetchApp.fetch(link).getBlob();
or the way of how I define the payload for the multipart/form-data content:
var payload = {
"file": img
};
How about this modification?
Modified script:
From:
var params = {
headers: {
"Content-Type": "multipart/form-data"
},
method: "post",
payload: payload,
muteHttpExceptions: true
};
To:
var params = {
method: "post",
payload: payload,
muteHttpExceptions: true
};
Additional information:
For example, if you want to add the text to the file, please use the following request body.
var payload = {
content: "sample text", // Added
file: img
};
var params = {
method: "post",
payload: payload,
muteHttpExceptions: true
};
Reference:
Webhook Resource
In my environment, I am using such request body. And it works fine. But if in your environment, it didn't work, please tell me. I would like to think of other solutions.
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?
I've been looking at this but it seems my problem is elsewhere. I am trying to upload a file. The input is currently defined as:
<input
type="file"
style="display: none;"
name="file"
multiple
nv-file-select
uploader="uploader">
This is how the upload is performed:
var uploader = $scope.uploader = new FileUploader({
url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});
uploader.onAfterAddingFile = function($modelFile) {
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
})
.then(
function (data) {
alert("upload success");
},
function (data, status) {
alert("upload error");
}
);
};
Whereas this is the Spring REST endpoint:
#PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
#RequestMapping(method=RequestMethod.POST, headers={"Content-Type=multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
LOGGER.debug("POST uploadModel");
return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK);
}
The problem is though, that an exception is getting thrown by Spring, telling me that the parameter file is not present:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
This is the request information:
How can I make this file upload work?
I guess it can be related to the content type
In your code i see this:
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
})
So you are defining an undefined content-type; You should set multipart/form-data
Try to put this content-type
I hope it's usefull
Angelo