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 { // MultipartFile:用来接受前端传过来的对象
String originalFilename = file.getOriginalFilename(); // 获取文件名称
String rootFilePath = System.getProperty("user.dir")+"/src/main/resources/files/"+originalFilename; //文件夹绝对路径
// 输入输出流:huttol提供
FileUtil.writeBytes(file.getBytes(),rootFilePath);
return Result.success();
}
}
/**
* 下载接口
* @param flag
* @param response
*/
@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("文件下载失败");
}
}
<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>
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/justleavel/article/details/122784577
内容来源于网络,如有侵权,请联系作者删除!