我想在前端上传之前裁剪图像(反应)

时间:2020-09-06 09:20:09

标签: javascript reactjs firebase react-hooks

这是产品表单组件,我想裁剪图像并上传而无需后端,然后将其上传到Firebase存储
我想自动或手动以恒定的宽高比进行裁剪以适合卡片,或者我想在卡片本身中进行裁剪,但是我尝试使用react-image-crop,但是我没有成功,它需要大量的设置并且我不需要知道怎么做

import React, { useState } from 'react'
import Input from '../../components/input/input.component'
import Button from '../../components/button/button.component'
import {db} from '../../firebase'
import './addproduct.styles.scss'
import { storage } from 'firebase'
import Spinner from '../../components/spinner/spinner.component'
const AddProduct = ({catigories}) => {
    const [name,setName] = useState('')
    const [price,setPrice] = useState('')
    const [catigory,setCatigory] = useState('')
    const [newCatigoryName,setNewCatigoryName] = useState('')
    const [newCatigoryImg,setNewCatigorImg] = useState(null)
    const [image,setImage] = useState(null)
    const [isSending,setIsSending] = useState(false)
    console.log(image)
    const handleSubmit = async (event) => {
        event.preventDefault()
        if(name && price  && image && catigory){
            setIsSending(true)
            if(catigory === 'addNewCatigory' && newCatigoryImg && newCatigoryName){
                await storage().ref().child(`catigories/${newCatigoryName}.jpg`).put(newCatigoryImg)
                const catigoryImgUrl = await storage().ref().child(`catigories/${newCatigoryName}.jpg`).getDownloadURL()
                await db.collection('catigories').doc(newCatigoryName).set({
                    name:newCatigoryName,
                    imgUrl:catigoryImgUrl
                })
                const storageId = `${name}-${price}-${catigory}`
                await storage().ref().child(`products/${storageId}.jpg`).put(image)
                const productImgUrl = await storage().ref().child(`products/${storageId}.jpg`).getDownloadURL()
                await db.collection('products').add({
                    name:name,
                    price: parseInt(price),
                    imgUrl:productImgUrl,
                    catigory:newCatigoryName
                })
                setIsSending(false)
            }else{
                const storageId = `${name}-${price}-${catigory}`
                await storage().ref().child(`products/${storageId}.jpg`).put(image)
                const productImgUrl = await storage().ref().child(`products/${storageId}.jpg`).getDownloadURL()
                await db.collection('products').add({
                    name:name,
                    price: parseInt(price),
                    imgUrl:productImgUrl,
                    catigory:catigory
                })
                setIsSending(false)
            }
        }
        
    }
    if(isSending){
        return <Spinner />
    }
    return (
        <div className='product'>
            <form onSubmit={handleSubmit} className="product__form">
                <Input placeholder='Enter Product Name' value={name} setValue={setName} width='100%' fontSize='20px' height='40px' borderRadius='20px'type='text' margin />            
                <Input placeholder='Product Price' value={price} setValue={setPrice} width='100%' fontSize='20px' height='40px' borderRadius='20px'type='number' margin />            
                <input type="file" onChange={(event) => event.target.files[0] ? setImage(event.target.files[0]) :null}/> 
                <select className='product__form__select' onChange={(event) => setCatigory(event.target.value)}>
                    <option value=''>Catigories</option>
                    {catigories.map(item => <option key={item.name} value={item.name}>{item.name}</option>)}
                    <option value='addNewCatigory'>other</option>
                </select>
                {catigory === 'addNewCatigory' ? 
                    <div className='product__form__addcatigory'>
                        <Input placeholder='Catigory Name' value={newCatigoryName} setValue={setNewCatigoryName} width='100%' fontSize='20px' height='40px' borderRadius='20px'type='text' margin />
                        <input type="file" onChange={(event) => event.target.files[0] ? setNewCatigorImg(event.target.files[0]) :null}/> 
                    </div>
                    : null
                }
                <Button title='add Item' width='100px' height='40px' style={{borderRadius:'20px'}}/>
            </form>
        </div>
    )
}

export default AddProduct

2 个答案:

答案 0 :(得分:0)

您可以在选择前端图像后裁剪图像。对于裁剪图像,这两个模块是最好的。

  1. React-easy-crop
  2. React-image-crop

这些模块的集成也很简单。

答案 1 :(得分:0)

我最近blogged关于如何使用react-uploady进行此操作。

查看此codesandbox以获得完整的示例。

该代码使用react-image-crop,但未以任何方式与其绑定,因此您可以将其替换为所需的任何其他作物解决方案。

它归结为:

import React, { useState, useCallback, useRef } from "react";
import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import Uploady, { withRequestPreSendUpdate } from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import UploadPreview from "@rpldy/upload-preview";
import cropImage from "./cropImage";

const ItemPreviewWithCrop = withRequestPreSendUpdate((props) => {
  const { url, updateRequest, requestData } = props;
  const [crop, setCrop] = useState({ aspect: 4 / 3 });

  const onUploadCrop = useCallback(async () => {
    if (updateRequest && (crop?.height || crop?.width)) {
      requestData.items[0].file = await cropImage(url, requestData.items[0].file, crop);
      updateRequest({ items: requestData.items });
    }
  }, [url, requestData, updateRequest, crop]);

  return (
    <>
      <ReactCrop
        src={url}
        crop={crop}
        onChange={setCrop}
        onComplete={setCrop}
      />
      <br/>
      <button onClick={onUploadCrop}>Upload Cropped</button>
    </>
  );
});

export default function App() {
  const previewMethodsRef = useRef();

  return (
    <Uploady destination={{ url: "[upload-url]" }} multiple={false}>
      <br />
      <UploadButton>Select File</UploadButton>
      <br />
      <UploadPreview
        PreviewComponent={ItemPreviewWithCrop}
        previewComponentProps={{ previewMethods: previewMethodsRef }}
        previewMethodsRef={previewMethodsRef}       
      />
    </Uploady>
  );
}

它将以固定的4/3纵横比在裁剪区域中显示所选文件(仅作为示例)。