Vue3使用ElementPlus中的el-upload手动上传并调用上传接口

前端代码

html 复制代码
	   <div class="upload-div">
          <el-upload
            v-model:file-list="form.fileImageList"
            ref="uploadRef"
            capture="false"
            action="#"
            accept="image/*"
            list-type="picture-card"
            :on-change="handleChange"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :multiple="true"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible" class="image-dialog">
            <img style="width: 100%;height: 100%" w-full :src="dialogImageUrl" alt="Preview Image"/>
          </el-dialog>
        </div>
typescript 复制代码
const fileBinaryList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const buttonLoading = ref(false);

const handleChange = (file, files) => {
  // file是当前上传的文件,files是当前所有的文件,
  fileBinaryList.value = files;
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

const handleRemove = (file) => {
  delImageByName(file.name).then(response => {
    proxy.$modal.msgSuccess("删除成功");
  }).finally(() => {
  });
}

function submitForm() {
 		let formData = new FormData();  //FormData中的参数
        formData.append('id', form.value.id);
        fileBinaryList.value.forEach((item) => {
          formData.append('files', item.raw);
        });
        uploadBinaryImage(formData);
        proxy.$modal.msgSuccess("修改成功");
}

前端定义接口

typescript 复制代码
export function uploadBinaryImage(data) {
  return request({
    url: '/update/update/uploadBinaryImage',
    method: 'post',
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

后端代码

实体类

java 复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: rattcs
 * @date: 2023/1/13
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UploadDto {

    private String id;

}

定义接口

java 复制代码
	/**
     * 上传二进制文件图片集合
     */
    @SaCheckPermission("update:update:uploadBinaryImage")
    @Log(title = "上传二进制文件图片", businessType = BusinessType.INSERT)
    @PostMapping("/uploadBinaryImage")
    public void uploadBinaryImage(@RequestBody @RequestParam("files") MultipartFile[] files, UploadDto bo) {
        iInvestigationRiverLakeDischargeOutletsService.uploadBinaryImage(files,bo);
    }

上传文件并插入数据库数据

java 复制代码
	@Value("${upload.dir}")
    private String UPLOAD_DIR;

	@Override
    public void uploadBinaryImage(MultipartFile[] files,UploadDto uploadDto) {
        String id = uploadDto.getId();
        for (MultipartFile file : files) {
            try {
                // 检查上传目录是否存在,不存在则创建
                File uploadDir = new File(UPLOAD_DIR);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                // 获取文件名
                String fileName = file.getOriginalFilename();
                String suffix = file.getOriginalFilename().split("\\.")[1];

                // 设置上传文件的保存路径
                String fileUploadName = java.util.UUID.randomUUID() + "." + suffix;
                Path filePath = uploadDir.toPath().resolve(fileUploadName);

                // 将文件复制到指定路径
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                investigationImageMapper
                    .insert(new InvestigationImage() {{
                        setInvestigationId(Long.valueOf(id));
                        setImageUrl(fileUploadName);
                        setImageName(fileUploadName);
                        setCreateTime(new Date());
                    }});
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
相关推荐
零凌林4 小时前
使用exceljs将excel文件转化为html预览最佳实践(完整源码)
前端·html·excel·vue3·最佳实践·文件预览·exceljs
岁岁岁平安1 天前
Vue3学习(组合式API——reactive()和ref()函数详解)
前端·javascript·vue.js·学习·vue3·reactive·ref
三天不学习1 天前
Vue3 本地环境 Vite 与生产环境 Nginx 反向代理配置方法汇总【反向代理篇】
运维·nginx·vue3·vite·反向代理
小张快跑。4 天前
【Vue3】使用vite创建Vue3工程、Vue3基本语法讲解
前端·前端框架·vue3·vite
halo14168 天前
vue中scss使用js的变量
javascript·vue3·scss
緑水長流*z8 天前
(14)Element Plus项目综合案例
vue.js·elementui·vue3·element plus·elementplus项目·完整项目案例·项目学习笔记
A-刘晨阳9 天前
Algolia - Docsearch的申请配置安装【以踩坑解决版】
vue3·ts·vuepress·algolia·docsearch
我是哈哈hh9 天前
【Vue】全局事件总线 & TodoList 事件总线
前端·javascript·vue.js·vue3·vue2
我是哈哈hh9 天前
【Vue】组件自定义事件 & TodoList 自定义事件数据传输
前端·javascript·vue.js·vue3·vue2
ʚʕ̯•͡˔•̯᷅ʔɞ LeeKuma10 天前
Vue3携手Echarts,打造炫酷数据可视化大屏
信息可视化·echarts·vue3