如何延迟将图像上传到S3?

如何解决如何延迟将图像上传到S3?

我正在研究“ uploadProductPage”,在这里我可以输入一些保存在mongoDB中的数据,并上传上传到Amazon S3的照片。我正在使用dropzone进行图像上载,选择文件后,它会立即上载到S3。我想将上传过程推迟到可能的时候再按“提交”按钮。

我的代码如下:

fileUpload.js

import React,{ useState } from 'react'
import Dropzone from 'react-dropzone';
import { Icon } from 'antd';
import Axios from 'axios';
import download from './download.jpeg'
  
  
function FileUpload(props) {
  
      const [Images,setImages] = useState([])
  
      const onDrop = (files) => {
  
      let formData = new FormData();
          const config = {
              header: {
                  'accept': 'application/json','Accept-Language': 'en-US,en;q=0.8','Content-Type': `multipart/form-data; boundary=${formData._boundary}`
              }
          }
          formData.append("profileImage",files[0])
          //save the Image we chose inside the Node Server 
          Axios.post('/api/photo/profile-img-upload',formData,config)
              .then(response => {
                if (response.data) {
                    alert('Saved')
                    setImages([...Images,response.data.imageName])
                    props.refreshFunction([...Images,response.data.image])

                } else {
                    alert('Failed to save the Image in Server')
                }
            })
    }


    const onDelete = (image) => {
        const currentIndex = Images.indexOf(image);

        let newImages = [...Images]
        newImages.splice(currentIndex,1)

        setImages(newImages)
        props.refreshFunction(newImages)
    }

    return (
        <div style={{ display: 'flex',justifyContent: 'space-between' }}>
            <Dropzone
                onDrop={onDrop}
                multiple={false}
                maxSize={800000000}
            >
                {({ getRootProps,getInputProps }) => (
                    <div style={{
                        width: '300px',height: '240px',border: '1px solid lightgray',display: 'flex',alignItems: 'center',justifyContent: 'center'
                    }}
                        {...getRootProps()}
                    >
                        {console.log('getRootProps',{ ...getRootProps() })}
                        {console.log('getInputProps',{ ...getInputProps() })}
                        <input {...getInputProps()} />
                        <Icon type="plus" style={{ fontSize: '3rem' }} />

                    </div>
                )}
            </Dropzone>

            <div style={{ display: 'flex',width: '300px',height: '300px'}}>

                {Images.map((image,index) => (
                    <div onClick={() => onDelete(image)}>
                        <img style={{ minWidth: '300px',height: '240px' }} src={download} alt={`productImg-${index}`} />
                    </div>
                ))}


            </div>

        </div>
    )
}

export default FileUpload

photo.js(路由器)

const express = require( 'express' );
const multer = require('multer');
const url = require('url');
const aws = require("aws-sdk");
const multerS3 = require("multer-s3");
const { auth } = require("../middleware/auth");
const path = require('path');
const router = express.Router();


const s3 = new aws.S3({
    accessKeyId: '',secretAccessKey: '',Bucket: 'uploads-111'
});

aws.config.update({
    secretAccessKey: process.env.S3_ACCESS_SECRET,accessKeyId: process.env.S3_ACCESS_KEY,region: "us-east-2",});

  const profileImgUpload = multer({
    storage: multerS3({
     s3: s3,bucket: 'uploads-111',acl: 'public-read',key: function (req,file,cb) {
      cb(null,path.basename( file.originalname,path.extname( file.originalname ) ) + '-' + Date.now() + path.extname( file.originalname ) )
     }
    }),limits:{ fileSize: 2000000 },// In bytes: 2000000 bytes = 2 MB
    fileFilter: function( req,cb ){
     checkFileType( file,cb );
    }
   }).single('profileImage');

function checkFileType(file,cb) {
    // Allowed ext
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    // Check mime
    const mimetype = filetypes.test(file.mimetype);
    if (mimetype && extname) {
        return cb(null,true);
    } else {
        cb('Error: Images Only!');
    }

if( mimetype && extname ){
    return cb( null,true );
   } else {
    cb( 'Error: Images Only!' );
   }
}

    router.post( '/profile-img-upload',( req,res ) => {
    profileImgUpload( req,res,( error ) => {
        // console.log( 'requestOkokok',req.file );
        // console.log( 'error',error );
        if( error ){
         console.log( 'errors',error );
         res.json( { error: error } );
        } else {
         // If File not found
         if( req.file === undefined ){
          console.log( 'Error: No File Selected!' );
          res.json( 'Error: No File Selected' );
         } else {
          // If Success
          const imageName = req.file.key;
          const imageLocation = req.file.location;
          res.json( {
            image: imageName,location: imageLocation
           } );
          }
         }
        });
       });

module.exports = router;

uploadProductPage.js

import React,{ useState } from 'react'
import { Typography,Button,Form,message,Input,Icon } from 'antd';
import FileUpload from '../../utils/FileUpload'
import Axios from 'axios';

const { Title } = Typography;
const { TextArea } = Input;

 
const Continents = [
    { key: 1,value: "1" },{ key: 2,value: "2" },{ key: 3,value: "3" },{ key: 4,value: "4" },{ key: 5,value: "5" },{ key: 6,value: "6" },{ key: 7,value: "7" }
]


function UploadProductPage(props) {

    const [TitleValue,setTitleValue] = useState("")
    const [DescriptionValue,setDescriptionValue] = useState("")
    const [PriceValue,setPriceValue] = useState(0)
    const [ContinentValue,setContinentValue] = useState([])

    const [Images,setImages] = useState([])


    const onTitleChange = (event) => {
        setTitleValue(event.currentTarget.value)
    }

    const onDescriptionChange = (event) => {
        setDescriptionValue(event.currentTarget.value)
    }

    const onPriceChange = (event) => {
        setPriceValue(event.currentTarget.value)
    }

    const onContinentsSelectChange = (event) => {
        setContinentValue(event.currentTarget.value)
    }

    const updateImages = (newImages) => {
        setImages(newImages)
    }
    const onSubmit = (event) => {
        event.preventDefault();


        if (!TitleValue || !DescriptionValue || !PriceValue ||
            !ContinentValue || !Images) {
            return alert('fill all the fields first!')
        }

        const variables = {
            writer: props.user.userData._id,title: TitleValue,description: DescriptionValue,price: PriceValue,images: Images,continents: ContinentValue,}

        Axios.post('/api/product/uploadProduct',variables)
            .then(response => {
                if (response.data.success) {
                    alert('Product Successfully Uploaded')
                    props.history.push({
                        pathname: "/user/cart",state: {
                          data: variables,},})
                } else {
                    alert('Failed to upload Product')
                }
            })

    }

    return (
        <div style={{ maxWidth: '700px',margin: '2rem auto' }}>
            <div style={{ textAlign: 'center',marginBottom: '2rem' }}>
                <Title level={2}> Upload Prompt </Title>
            </div>


            <Form onSubmit={onSubmit} >

                {/* DropZone */}
                <FileUpload refreshFunction={updateImages} />

                <br />
                <br />
                <label>Subject</label>
                <Input
                    onChange={onTitleChange}
                    value={TitleValue}
                />
                <br />
                <br />
                <label>Title</label>
                <Input
                    onChange={onDescriptionChange}
                    value={DescriptionValue}
                />
                <br />
                <br />
                <label>Pages</label>
                <Input
                    onChange={onPriceChange}
                    value={PriceValue}
                    type="number"
                />
                <br /><br />
                <label>Due Date</label>
                <br /><br />
                <Input onChange={onContinentsSelectChange} value={ContinentValue}
                    type="date"
                />
                <br />
                <br />
                <Button
                    onClick={onSubmit}
                >
                    Submit
                </Button>
            </Form>
        </div>
    )
}

export default UploadProductPage

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res