Reputation: 43
I am using react-dropzone and cloudinary for image upload.
I have already made an successfull connection between my account and my react project and I am able to upload images though my react project.
I am having trouble setting the file name in the react project.
Here is the code snipped of my react project.
I have already tried something like this:
onImageDrop(files) {
console.log(files)
var test = JSON.parse(JSON.stringify(files))
test[0]["name"] = "test"
this.handleImageUpload(test);
}
But I get an error saying that the file is readonly.
Here is the working example of what I have
onImageDrop(files) {
this.handleImageUpload(files[0]);
}
handleImageUpload(file) {
let upload = request.post(CLOUDINARY_UPLOAD_URL)
.field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
.field('file', file);
upload.end((err, response) => {
if (err) {
console.error(err);
}
console.log(response)
});
}
render() {
return (
<div>
<Dropzone
onDrop={this.onImageDrop.bind(this)}cloudinary
accept="image/*"
multiple={false}>
{({ getRootProps, getInputProps }) => {
console.log("input props", getInputProps)
return (
<div
{...getRootProps()}
>
<input {...getInputProps()} />
{
<p>Try dropping some files here, or click to select files to upload.</p>
}
</div>
)
}}
</Dropzone>
</div>
)
}
How do I change the file name before I send it to cloudfire?
Upvotes: 3
Views: 4130
Reputation: 301
You can set the image name on Cloudinary when uploading by setting the public_id.
For example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Upload extends React.Component {
processFile = async e => {
var file = e.target.files[0];
var formdata = new FormData();
formdata.append("file", file);
formdata.append("cloud_name", "XXXX");
formdata.append("upload_preset", "XXXX");
formdata.append("public_id", "my-name1");
let res = await fetch(
"https://api.cloudinary.com/v1_1/<Cloud-Name>/auto/upload",
{
method: "post",
mode: "cors",
body: formdata
}
);
let json = await res.json();
console.log(JSON.stringify(json.secure_url));
};
render() {
return (
<div>
<h3>Upload</h3>
<input type="file" onChange={this.processFile} />
</div>
);
}
}
ReactDOM.render(<Upload />, document.getElementById("container"));
Upvotes: 4