react 实现图片上传功能

首先我们需要进入ant-design文档中,找到upload组件

import React from "react";
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ fileList }) => this.setState({ fileList });

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action={`${HOST}:${PORT}/goods/upload`}  //和后台接口对应一致,这是我自己的接口,大家自行设置
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

这样一个简单的上传页面就能看到了
在这里插入图片描述
那么接下来如何实现将图片发送到后台服务器?

第一步:下载connect-multiparty组件
第二步: 导入上传中间件并创建上传中间件对象

const multiparty = require('connect-multiparty'); 
const multipartyMiddleWare = multiparty(); 

图上上传接口:goodsapi.js

/*
   图片上传接口:http://localhost:8089/goods/upload
*/
router.post('/upload',multipartyMiddleWare,(req, res) => {
    //输出上传文件的名称(测试)
    console.log("上传文件名:",req.files.photoContent.name)
    //获取上传文件
    let file = req.files.photoContent;   //将上传文件保留在临时文件中
    //设置上传文件的保存位置
    let desc_dir = path.join(__dirname+'../../../public/images')+'\\'+file.originalFilename
    console.log("保存路径:",desc_dir)
    //将临时文件中的数据复制到保存位置
    fs.readFile(file.path,function (err,data) {
        fs.writeFile(desc_dir,data,function (err) {
            if (err){
                console.log(err)
                res.json({
                    code: 1002,
                    msg: '写入文件失败'
                })
            }
        })
    })

    //将上传图片的存储路径响应给客户端
    res.json({
        code: 1000,
        ImgPath: `http://localhost:8089/images/${file.originalFilename}`//网络访问时,public是虚拟目录,不需要写出来
    })
})

图片上传成功后在后台服务器能呈现出来文件名
在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Ant Design 的 Upload 组件来实现图片上传功能。首先,需要安装 Ant Design: ``` npm install antd ``` 然后,在你的 React 组件中引入 Upload 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; class Avatar extends React.Component { state = { loading: false, imageUrl: '' }; handleChange = info => { if (info.file.status === 'uploading') { this.setState({ loading: true }); return; } if (info.file.status === 'done') { // Get this url from response in real world. getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl, loading: false, }), ); } }; render() { const { loading, imageUrl } = this.state; const uploadButton = ( <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} <div className="ant-upload-text">Upload</div> </div> ); return ( <Upload name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false} action="https://www.mocky.io/v2/5cc8019d300000980a055e76" beforeUpload={beforeUpload} onChange={this.handleChange} > {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton} </Upload> ); } } ``` 这个例子中,我们定义了一个 Avatar 组件,其中包含一个 Upload 组件。我们设置了 Upload 组件的 name、listType、className、showUploadList、action、beforeUpload 和 onChange 属性。其中: - name 表示上传文件的参数名; - listType 表示上传列表的样式,这里设置为 picture-card; - className 表示 Upload 组件的类名; - showUploadList 表示是否显示上传列表; - action 表示上传的 URL; - beforeUpload 是一个函数,用于上传前的校验; - onChange 是一个函数,用于上传后的处理。 在 handleChange 函数中,我们根据上传文件的状态来处理上传结果,并将图片的 base64 编码保存到 state 中。最后,我们将图片显示出来,如果没有上传图片,则显示上传按钮。 在 beforeUpload 函数中,我们可以进行上传前的校验。例如,限制上传图片的大小和类型: ```jsx function beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; } ``` 这个例子中,我们限制上传图片的类型为 JPG 和 PNG,大小不超过 2MB。 最后,需要引入 message、LoadingOutlined 和 PlusOutlined 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; ``` 这样,就可以使用 Ant Design 的 Upload 组件实现图片上传功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值