图片上传

2 篇文章 0 订阅

图片上传功能

  • 首先记录一下将本地图片转换成网络可以访问的地址,写一个配置类实现WebMvcConfigurer接口,重写addResourceHandlers方法,如图:
    在这里插入图片描述

其中 /images/** 将代替本地磁盘路径 F:/workspaces/images/cartoon/

举个例子:
访问 http://localhost:8082/images/user/icons/8.png
相当于访问本地路径 F:\workspaces\images\cartoon\user\icons\8.png

  1. FormData对象来存储图片,在如果直接打印 console.log(formData) 的话会前台会显示为空,而后台却可以正常接收到数据,前台如果想要打印信息的话 console.log(formData.get(‘file’))

前台

//<template>
	<el-upload class="avatar-uploader"
        action="123"
        :http-request="upLoad"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="headUrl"
          :src="headUrl"
          class="avatar">
        <i v-else
          class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
//<script>
	upLoad(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      systemManage.upload(formData).then(res => {
        this.headUrl = res.data
      })
	}
//app.js
// 上传头像
  upload(obj) {
    let data = obj
    return axios({
      url: serverUrl + '/home/userManagement/upload',
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
        // 'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: data
    })
  }

后台

	public String upload(MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = System.currentTimeMillis() + "." + suffix;
        String basePath = "F:\\workspaces\\images\\cartoon\\" ;
        String relativePath = "temp\\user\\icons";
        String path = basePath + relativePath + File.separator + fileName;
        Util.uploadImage(path,file);
        String imageUrl = "http://localhost:8082/images/" + relativePath + File.separator + fileName;
        imageUrl = imageUrl.replace("\\","/");
        return imageUrl;
    }


	/**
     * 上传图片
     * @param path      图片存储本地磁盘位置
     * @param file      图片
     */
    public static void uploadImage(String path, MultipartFile file){
        File newFile = new File(path);
        // 可能目录不存在,就创建
        newFile.getParentFile().mkdirs();
        try {
            file.transferTo(newFile);
            System.out.println("上传图片成功");
        }catch (Exception e){
            System.out.println("上传图片失败");
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值