vue elementui springboot 单张图片上传


@RestController
@RequestMapping("/file")
public class FileUploadController {
    private String imgString;
    // 设置保存地址(这里是转义字符)
    private  String filePath="D:\\DingDing\\";
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        // 判断文件是否为空
        if(file.isEmpty()){
            return Result.warn("上传文件不能为空");

        }
        // 获取传过来的文件名字
        String OriginalFilename=file.getOriginalFilename();
        //判断文件类型
        String type = OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1).toLowerCase();
        if (!type.equals("jpg")&&!type.equals("png")&&!type.equals("jpeg")){
            return  Result.warn("不是jpg或png");
        }
        // 为了防止重名覆盖,获取系统时间戳+原始文件的后缀名
        String fileName=System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
        File dest=new File(filePath+fileName);
        imgString = "http://localhost:8081/myimg/"+fileName;
        // 判断文件是否存在
        if(!dest.getParentFile().exists()){
            // 不存在就创建一个
            dest.getParentFile().mkdirs();
        }
        try {
            // 上传
            file.transferTo(dest);
            return Result.success("上传成功",imgString);
        }catch (Exception e){
            e.printStackTrace();
            return  Result.warn("上传失败");
        }
    }
    @PostMapping("/uploads")
    public Result uploadFiles(@RequestParam("files") MultipartFile[] files){
        String img = "";
        File fileDir = new File(filePath);
        if (!fileDir.exists() && !fileDir.isDirectory()){
            fileDir.mkdirs();
        }
        if (files !=null && files.length>0){
            for (int i =0;i<files.length;i++){
                String OriginalFilename=files[i].getOriginalFilename();
                System.out.println("文件名为:"+OriginalFilename);
                String fileName=System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
                File dest=new File(filePath+fileName);
                imgString = "http://localhost:8081/myimg/"+fileName;
                try {
                    files[i].transferTo(dest);
                    if (img.equals("")){
                        img=imgString;
                    }else {
                        img = img+";"+imgString;
                    }
                }catch (IOException e){
                    e.printStackTrace();
                    return  Result.warn(e.getMessage());
                }
            }
        }else {
            return  Result.warn("文件为0");
        }
        return Result.success("上传成功",img);
    }
}

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/myimg/**").addResourceLocations("file:D:/DingDing/");
        super.addResourceHandlers(registry);
    }

}

vue前端

<el-form-item label="头像" prop="portrait">
          <el-upload
            action="http://localhost:8081/file/upload"
            list-type="picture"
            :show-file-list="false"
            :on-remove="handlePreview"
            :on-change="uploadSectionFile"
            :on-success="success"
            :limit="1"
            ref="businessLicense">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-image style="width: 100px; height: 100px" :src="ruleForm.portrait"></el-image>
        </el-form-item>


success (response, file) {
      if (response.code === 200) {
        this.ruleForm.portrait = response.data
        sessionStorage.setItem('imgUrl', this.ruleForm.portrait)
      }
    },
    uploadSectionFile (file) {
      this.ruleForm.portrait = file.url
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension =
        testmsg === 'jpg' ||
        testmsg === 'JPG' ||
        testmsg === 'png' ||
        testmsg === 'PNG'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!extension) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return extension && isLt2M
    },
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值