[英]How to image resize before upload Dropzone in Reactjs?
我使用了react-dropzone但这个包不支持 rezise。 如何调整图像并上传它?
const { getRootProps, getInputProps, acceptedFiles, rejectedFiles } = useDropzone({
multiple: props.multiple,
accept: props.acceptedFileTypes,
maxFilesize: 100,
onDrop: acceptedFiles => {
if (acceptedFiles.length > 0) {
// i uploaded images.
upload(acceptedFiles)
}
}
更新了我的答案,改为引用 imtool(这是具有不同 API 和更多功能的钉子)。 原答案如下。
要解决这个问题,您可以使用imtool ,它是对钉子的精神继承者。
更新示例:
//...other imports
import { fromImage } from 'imtool';
const [ fileURL, setFileURL ] = useState(null);
const reader = new FileReader();
reader.addEventListener("load", function () {
setFileURL(reader.result);
}, false);
useEffect(() => {
if (acceptedFiles[0]) {
reader.readAsDataURL(acceptedFiles[0]);
}
}, [ acceptedFiles ]);
useEffect(() => {
if (fileURL) {
// Parameters: 250 is the maximum size and false is the cover argument.
fromImage(fileURL)
.then(tool => tool.thumbnail(250, false).toBlob())
.then(blob => {
// You can add the resulting blob to a FormData element and then send that.
const formData = new FormData();
form.append('image', blob, 'image.jpg');
fetch('https://example.com/image', { method: 'POST', body: formData });
}
.catch(e => /* Do something with the error! */);
}
}, [ fileURL ]);
有关文档,请参阅此 GitHub 存储库中的 README。
前段时间我制作了一个库来执行这个确切的任务。
它可以在 npm -nailit 上使用(我刚刚推送了一个更新,请确保您获得 2.0.1 版本)。 这是一个带有nailit和react-dropzone的示例项目: https : //github.com/mat-sz/nailit-demo
它的工作原理是在 Web 浏览器中创建画布并调整图像大小。
例子:
const [ fileURL, setFileURL ] = useState(null);
const reader = new FileReader();
reader.addEventListener("load", function () {
setFileURL(reader.result);
}, false);
useEffect(() => {
if (acceptedFiles[0]) {
reader.readAsDataURL(acceptedFiles[0]);
}
}, [ acceptedFiles ]);
useEffect(() => {
if (fileURL) {
// Parameters: file data URI, options and should output be a blob (if you want to POST it then yes)
nailIt(fileURL, {
maxSize: 250,
cover: false,
outputType: 'image/jpeg',
outputQuality: 0.7
}, true).then((blob) => {
// You can add the resulting blob to a FormData element and then send that.
const formData = new FormData();
form.append("image", blob, "image.jpg");
fetch('https://example.com/image', { method: 'POST', body: formData });
});
}
}, [ fileURL ]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.