首先在后端新建一个controller:
代码:
package com.example.demo.controller;
import cn.hutool.core.io.FileUtil;
import com.example.demo.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/files")
public class FileController {
@PostMapping("/upload")
public Result<?> upload(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String rootFilePath = System.getProperty("user.dir")+"/src/main/resources/files/"+originalFilename;
FileUtil.writeBytes(file.getBytes(),rootFilePath);
return Result.success();
}
}
我们这里使用了hutool工具类里面封装的方法,可以直接文件上传
在代码中都写好了注释,同时我们需要新建一个files文件夹用来存放文件
然后我们使用postman测试:
测试成功!后端已经写好了接口
下载接口:
@GetMapping("/{flag}")
public void getFiles(@PathVariable String flag, HttpServletResponse response) {
OutputStream os;
String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";
List<String> fileNames = FileUtil.listFileNames(basePath);
String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
try {
if (StrUtil.isNotEmpty(fileName)) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(basePath + fileName);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}
postman测试:
然后将data地址搜索就会自动下载图片
然后写前台代码:
首先新增图片展示:
使用element-plus中的图片和上传就可以实现:
<el-form-item label="封面">
<el-upload ref="upload" action="http://localhost:8099/files/upload" :on-success="filesUploadSuccess">
<el-button type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
展示:
<el-table-column
label="封面">
<template #default="scope">
<el-image
style="width: 100px; height: 100px"
:src="scope.row.cover"
:preview-src-list="[scope.row.cover]"
:initial-index="4"
fit="cover"
>
</el-image>
</template>
</el-table-column>
|