SSM + Vue + Element UI 图片上传 服务器

图片显示:点我查看

SSM 准备工作

一、准备文件上传的jar包

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

二、配置Spring MVC 配置文件

放在beans中

<bean id="multipartResolver"
	  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 设置上传文件的最大尺寸为5MB -->
	<property name="maxUploadSize">
		<value>5242880</value>
	</property>
	<property name="defaultEncoding">
		<value>UTF-8</value>
	</property>
</bean>

三、编写 Controller 接收文件

@RequestMapping("/uploadImage")
public String megerUserShopImg(MultipartFile file) {
    //判断所上传文件是否存在
    if (file.isEmpty()) {
        return "上传错误";
    }
    //获取上传文件的原始名称
    String originalFilename = file.getOriginalFilename();
    //设置上传文件的保存地址目录
    String dirPath = "D:/user/";
    File filePath = new File(dirPath);
    //如果保存的地址不存在,就先创建目录
    if (!filePath.exists()) {
        filePath.mkdirs();
    }
    //获取当前文件的后缀
    String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    //使用UUID重新命名上传的文件名称(UUID(唯一识别码)+原始文件名称后缀)
    String newFileName = UUID.randomUUID() + "." + suffix;
    try {
        //创建可能会有错误,强制添加异常
        file.transferTo(new File(dirPath + newFileName));
    } catch (IOException e) {
        e.printStackTrace();
        return "上传错误";
    }
    System.out.println(dirPath + newFileName);
    return newFileName;
}

Vue + Element UI 图片上传组件

upload中最重要的三个参数

参数作用
name后台接收的参数(没有会报错)
action后台请求路径地址(http://localhost:8080/user/uploadImage)
on-success访问成功调用的参数
<!-- 主要文件上传部分 -->
<el-upload
  class="upload-demo"
  name="file"
  action="/api/user/uploadImage"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="9"
  :on-success="handleSuccess"
  :on-exceed="handleExceed"
>
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">
    只能上传jpg/png文件,且不超过5MB
  </div>
</el-upload>

<!-- 主要返回事件部分 -->
//成功返回方法
handleSuccess(res, file) {
  this.$message({
    type: "info",
    message: "图片上传成功",
    duration: 6000,
  });
  console.log(res);
},
handleRemove(file, fileList) {
  console.log(file, fileList);
},
handlePreview(file) {
  console.log(file);
},
handleExceed(files, fileList) {
  this.$message.warning(
    `请勿频繁上传图片操作,您已经选择 ${files.length} 个文件,真的需要重新上传,请刷新页面`
  );
},
beforeRemove(file, fileList) {
  return this.$confirm(`确定移除 ${file.name}?`);
},

最后

在进行一些业务处理即可

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值