antd upload上传图片前后台代码实现

1、引入antd上传图片需要的包

import React, { Component } from 'react';
import {  Upload, Icon, message } from 'antd';

import reqwest from 'reqwest';

2、前端实现代码

class Register extends Component {
state = {
    loading: false,
  };
render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const { imageUrl } = this.state;

    const props = {
      name: "avatar",
      showUploadList: false,//设置只上传一张图片,根据实际情况修改
      customRequest: info => {//手动上传
        const formData = new FormData();
        formData.append('avatar', info.file);//名字和后端接口名字对应
        reqwest({
          url: 'http://localhost:8080/user/uploadImage',//上传url
          method: 'post',
          processData: false,
          data: formData,
          success: (res) => {//上传成功回调
            if (res.code === '0') {
              this.setState({
                imageUrl: res.imageUrl
              });
              message.success('上传成功!');
            }
          },
          error: () => {//上传失败回调
            message.error('上传失败!');
          },
        });
      },
      onRemove: file => {//删除图片调用
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      listType: "picture-card",
      className: "avatar-uploader",

      beforeUpload: file => {//控制上传图片格式
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
          message.error('您只能上传JPG/PNG 文件!');
          return;
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('图片大小必须小于2MB!');
          return;
        }
        return isJpgOrPng && isLt2M;
      },
    };
}

    return (
    <div className={styles.main}>
       <Upload {...props}>
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> :     uploadButton}
       </Upload>
    </div>
    )
}

 3、后端代码实现

@RestController
@RequestMapping("/user")
public class UserController {

     /**
     * 图片上传
     */
    @RequestMapping(value = "/uploadImage",method = RequestMethod.POST)
    @ResponseBody
    public R uploadImage(@RequestParam(value = "avatar") MultipartFile avatar){

        Map<String,Object> map = new HashMap<>();
        if (avatar.isEmpty()) {
            return R.error();
        }else {

            //保存时的文件名
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String dateName = df.format(calendar.getTime())+avatar.getOriginalFilename();

            //保存文件的绝对路径
            WebApplicationContext webApplicationContext = (WebApplicationContext) SpringContextUtils.applicationContext;
            ServletContext servletContext = webApplicationContext.getServletContext();
            String realPath = servletContext.getRealPath("/");

            String filePath = realPath + "WEB-INF"+File.separator + "classes" + File.separator +"static" + File.separator + "resource" + File.separator+dateName;//此路径是放在tomcat war包的绝对路径
            File newFile = new File(filePath);
            System.out.println("filePath=:"+filePath);
            //MultipartFile的方法直接写文件
            try {

                //上传文件
                avatar.transferTo(newFile);

                //数据库存储的相对路径
                String projectPath = servletContext.getContextPath();
                HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
                String contextpath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+projectPath;
                String url = contextpath + "/resource/"+dateName;//此路径是放在tomcat war包的相对路径
                //文件名与文件URL存入数据库表
                System.out.println("url=:"+url);
                map.put("imageUrl",url);//返回前台
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        return R.ok(map);
    }   
}

4、整个上传过程结束。

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值