首页 > 解决方案 > 图片没有上传到网站上

问题描述

我做了两个相同的功能来上传和图像,第二个功能是上传额外的图像。第一个工作完美,但imageSecond剂量正常工作。

当我上传image它时它工作得很好但是当我上传imageSecond它时它工作正常请我被困在这里很长时间我真的需要一些帮助。

另外,我将 django 用于后端并为前端做出反应。

这是代码:

ProductEditScreen.js:

    const ProductEditScreen = ({ match, history }) => {

    const productId = match.params.id
    
    const [name, setName] = useState('')
    const [price, setPrice] = useState(0)
    const [image, setImage] = useState('')
    const [imageSecond, setImageSecond] = useState('')
    const [brand, setBrand] = useState('')
    const [category, setCategory] = useState('')
    const [countInStock, setCountInStock] = useState(0)
    const [description, setDescription] = useState('')
    const [uploading, setUploading] = useState(false)
    

    const dispatch = useDispatch()
    
    const productDetails = useSelector(state => state.productDetails)
    const { error, loading, product } = productDetails
    
    const productUpdate = useSelector(state => state.productUpdate)
    const { error: errorUpdate, loading: loadingUpdate, success: successUpdate } = productUpdate
    
        
    useEffect(() => {

        if(successUpdate){
            dispatch({type: PRODUCT_UPDATE_RESET})
            history.push('/admin/productlist')
        }else {
            if (!product.name || product._id !== Number(productId)) {
                dispatch(listProductDetails(productId))
            } else{
                setName(product.name)
                setPrice(product.price)
                setImage(product.image)
                setImageSecond(product.imageSecond)
                setBrand(product.brand)
                setCategory(product.category)
                setCountInStock(product.countInStock)
                setDescription(product.description)
            }
        }

    }, [dispatch, product, productId, history, successUpdate])

    const submitHandler = (e) => {
        e.preventDefault()
        dispatch(updateProduct({
            _id: productId,
            name,
            price,
            image,
            imageSecond,
            brand,
            category,
            countInStock,
            description,
        }))
    }

    const uploadFileHandler = async (e) => {
        const file = e.target.files[0]
        const formData = new FormData()

        formData.append('image', file)
        formData.append('product_id', productId)

        setUploading(true)

        try{
            const config = {
                headers:{
                    'content-type': 'multipart/form-data'
                }
            }

            const {data} = await axios.post('/api/products/upload/', formData, config)
            console.log(data)

            setImage(data)
            setUploading(false)


        }catch(error){
            setUploading(false)
        }
    }

    const uploadFileHandlerSecond = async (e) => {
        const file = e.target.files[0]
        const formData = new FormData()

        formData.append('imagesecond', file)
        formData.append('product_id', productId)

        setUploading(true)

        try{
            const config = {
                headers:{
                    'content-type': 'multipart/form-data'
                }
            }

            const {data} = await axios.post('/api/products/upload/', formData, config)
            console.log(data)
            setImageSecond(data)
            setUploading(false)


        }catch(error){
            setUploading(false)
        }
    }
    



      return (
       <div>

        <Link to='/admin/productlist'>
            Go Back
        </Link>

        <FormContainer>
            <h1>EDIT PRODUCT</h1>
            {loadingUpdate && <Loader/>}
            {errorUpdate && <Message variant='secondary'>{errorUpdate}</Message>}

            {loading ? <Loader/> : error ? <Message variant='secondary'>{error}</Message> 
            : (
                <Form onSubmit={submitHandler}>

                    <Form.Group controlId='name'>
                        <Form.Label>Name</Form.Label>
                        <Form.Control
                            type='name'
                            placeholder='Enter Name'
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                        >
                        </Form.Control>
                    </Form.Group>


                    <Form.Group controlId='price'>
                        <Form.Label>Price</Form.Label>
                        <Form.Control
                            type='number'
                            placeholder='Enter Price'
                            value={price}
                            onChange={(e) => setPrice(e.target.value)}
                        >
                        </Form.Control>
                    </Form.Group>


                    <Form.Group controlId='image'>
                        <Form.Label>Image</Form.Label>
                        <Form.Control
                            type='text'
                            placeholder='Set Image'
                            value={image}
                            onChange={(e) => setImage(e.target.value)}
                        >
                        </Form.Control>

                        <Form.File
                            id='image-file'
                            label='Choose File'
                            custom
                            onChange={uploadFileHandler}
                        >

                        </Form.File>
                        {uploading && <Loader />}

                    </Form.Group>


                    <Form.Group controlId='imagesecond'>
                        <Form.Label>Second Image</Form.Label>
                        <Form.Control
                            type='text'
                            placeholder='Set Second Image (optional)'
                            value={imageSecond}
                            onChange={(e) => setImage(e.target.value)}
                        >
                        </Form.Control>

                        <Form.File
                            id='imagesecond-file'
                            label='Choose File'
                            custom
                            onChange={uploadFileHandlerSecond}
                        >

                        </Form.File>
                        {uploading && <Loader />}

                    </Form.Group>

  
                    <Form.Group controlId='brand'>
                        <Form.Label>Brand</Form.Label>
                        <Form.Control
                            type='text'
                            placeholder='Enter Brand'
                            value={brand}
                            onChange={(e) => setBrand(e.target.value)}
                        >
                        </Form.Control>
                    </Form.Group>


                    <Form.Group controlId='countinstock'>
                        <Form.Label>Stock</Form.Label>
                        <Form.Control
                            type='number'
                            placeholder='Total Stock'
                            value={countInStock}
                            onChange={(e) => setCountInStock(e.target.value)}
                        >
                        </Form.Control>
                    </Form.Group>


                    <Form.Group controlId='category'>
                        <Form.Label>Category</Form.Label>
                        <Form.Control
                            type='text'
                            placeholder='Enter Category'
                            value={category}
                            onChange={(e) => setCategory(e.target.value)}
                        >
                        </Form.Control>
                    </Form.Group>


                    <Form.Group controlId='description'>
                        <Form.Label>Description</Form.Label>
                        <textarea
                            className='w-100 rounded'
                            rows='4'
                            type='text'
                            placeholder='Enter Description'
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                        >
                        </textarea>
                    </Form.Group>



                    <Button type='submit' variant='primary'>
                        Update
                    </Button>


            </Form>
            )}

        </FormContainer>
    </div>
)
}

export default ProductEditScreen

产品视图.py:

@api_view(['POST'])
def uploadImage(request):
data = request.data

product_id = data['product_id']
product = Product.objects.get(_id=product_id)

product.image = request.FILES.get('image')
product.save()
return Response('Image was uploaded')


@api_view(['POST'])
def uploadImageSecond(request):
data = request.data

product_id = data['product_id']
product = Product.objects.get(_id=product_id)

product.imageSecond = request.FILES.get('imagesecond')
product.save()
return Response('Image was uploaded')

网址.py:

from django.urls import path
from base.views import product_views as views


urlpatterns = [
path('', views.getProducts, name="products"),
path('create/', views.createProduct, name="product-create"),
path('upload/', views.uploadImage, name="image-upload"),

path('<str:pk>/', views.getProduct, name="product"),
path('update/<str:pk>/', views.updateProduct, name="product-update"),
path('delete/<str:pk>/', views.deleteProduct, name="product-delete"),
]

标签: javascriptreactjsdjangodjango-modelsfile-upload

解决方案


您必须定义两个不同的 URL 来上传文件,一个为您的uploadImage,一个为您uploadImageSecond的,例如

urlpatterns = [
 path('upload/', views.uploadImage, name="image-upload"),
 path('uploadImageSecond/', views.uploadImageSecond, name="uploadImageSecond"), 
]

并在您的前端提供这两个不同的网址


推荐阅读