1.封装文件工具类FileUtils
import .IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
public class FileUtils {
/**
* 上传文件到本地服务器,并返回文件的全路径。
*
* @param basePath 文件保存的基础路径
* @param file 待上传的文件
* @return 上传后文件的全路径
*/
public String uploadFile(String basePath, MultipartFile file) {
try {
// 确保basePath以路径分隔符结尾,如果不是则添加
if (!basePath.endsWith(File.separator)) {
basePath += File.separator;
}
// 生成唯一的文件名,防止重名覆盖
String originalFilename = file.getOriginalFilename();
String uniqueFileName = UUID.randomUUID().toString() + "_" + originalFilename;
Path uploadPath = Paths.get(basePath, uniqueFileName);
// 创建文件夹路径(如果不存在)
Files.createDirectories(uploadPath.getParent());
// 将上传的文件保存到服务器
Files.copy(file.getInputStream(), uploadPath);
// 返回文件的全路径
return uploadPath.toString();
} catch (IOException e) {
// 处理文件上传过程中可能出现的IO异常
e.printStackTrace();
throw new RuntimeException("文件上传失败", e);
}
}
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024 * 10];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
os.flush();
}
}
catch (IOException e)
{
throw e;
}
finally
{
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(fis);
}
}
}
2.service层业务方法调用,要先在yml配置好上传路径
@Value("${web.upload-path}")
private String uploadPath;
public String uploadFile(MultipartFile file, HttpServletRequest request) {
FileUtils fileUtils = new FileUtils();
String filePath = fileUtils.uploadFile(uploadPath, file);
return filePath;
}
}
3.controller层接口
@PostMapping("uploadFile")
public Result uploadFile(@RequestBody MultipartFile file, HttpServletRequest request) {
try {
String filePath = filesService.uploadFile(file, request);
return new Result().ok().setData(filePath);
} catch (Exception e) {
e.printStackTrace();
return new Result().err();
}
}
4.前端代码实现
<el-form-item label="交付物:" prop="file">
<el-upload ref="uploadRef" class="upload-demo" action="/sys/files/uploadFile"
:on-success="handleFile" :on-remove="handleRemove" :limit="1" :file-list="fileList"
:auto-upload="false" :on-exceed="handleExceed">
<template #trigger>
<el-button type="primary" icon="el-icon-upload">请选择文件</el-button>
</template>
<el-button type="success" @click="submitUpload">上传</el-button>
<template #tip>
<div class="el-upload__tip" style="color: hsla(60, 59%, 49%, 0.962)">
tip:文件大小不要超过2M
</div>
</template>
</el-upload>
</el-form-item>
效果如下
