项目中需要做一个内容的封面图片,后台有上传管理的功能。

这里我用的

这个,复制组件代码,因为我只需要上传一个图片,所以将长度改为 1 

重点说一下图片上传的请求方式

原生组件代码是用的action属性+url上传到后台的。这种方式不太适合我的功能需求,所以需要重新上传方法

api里有cunstomRequest属性可以帮助我们实现重写上传方法,并且会覆盖原有的action上传方式4

<template>
<a-upload
          listType="picture-card"
          :fileList="fileList"
          @preview="handlePreview"
          @change="handleChange"
          :customRequest="customRequest"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">Upload</div>
          </div>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</template>

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 {
    data() {
      return {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        fileType: ''
      }
    },
    methods: { 
      handleCancel() {
        this.previewVisible = false;
      },
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
      },
      handleChange({ fileList }) {
        this.fileList = fileList;
      },
    customRequest (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        formData.append('fileType', this.fileType)//这里可以添加一些向后台传递的参数
        this.saveFile(formData,data)
      },
      saveFile (formData,data) {
        let that = this
        this.$upload('这里填写url地址', formData).then((response) => {
          this.filename = response.data.name
          data.onSuccess();//后台返回成功后一定要调用data里的onSuccess方法,不然会一直显示在上传中,导致无法回显图片
        }).catch((error) => {
          data.onError() //上传失败
        })
      }
    },
  };
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>

效果

成功

点击查看

删除就删除了。我这里删除也是请求的后台删除方法。

下面是后台上传和删除的代码

需要先设置本地磁盘存放的路径映射,放到bean容器中,我这里是springboot,所以简化了配置,加一个注解就好了。


@Component
public class WebMvcConfiguration implements WebMvcConfigurer {
    /**
     * 虚拟路径配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //这里配置了映射路径之后,可以在浏览器输入localhost:8080/files/图片全称+文件后缀
        registry.addResourceHandler("/files/**").addResourceLocations("file:/D:/files/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

}
@ApiOperation(value = "上传文件")
        @PostMapping(value = "/fileUpload")
        public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model,HttpServletRequest request) {
            if (file.isEmpty()) {
                System.out.println("文件为空空");
            }
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "D://files//"; // 上传后的路径
            String fileid = UUID.randomUUID().toString();
            fileName = fileid + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String filename = "/files/" +  fileName;
            model.addAttribute("uid", fileid);
            model.addAttribute("name", fileid+suffixName);
            Map<String,String> response = new HashMap<>();
            response.put("status","success");
            model.addAttribute("response",response);
            return JSONObject.toJSONString(model);
        }


@ApiOperation(value = "删除文件")
    @DeleteMapping(value = "/fileDelete")
    public String fileDelete(String filename,Model model, HttpServletRequest request) {
        File file = new File("D://files//"+filename);
        if (file.exists()){
            try {
                file.delete();
                model.addAttribute("status","成功");
            }catch (Exception e){
                model.addAttribute("status","失败");
            }
        }else{
            model.addAttribute("status","文件不存在");
        }
        return JSONObject.toJSONString(model);
    }

 

this.ok

Logo

前往低代码交流专区

更多推荐