直接贴代码
public class UploadFileToService {
public static String upload(MultipartFile file, String savePath) {
// 新文件名长度
int newFilenameLength = 16;
// 新文件名组合类型
int newFilenameType = RandomStringUtil.FIGURE_LOWER_CASE_POWER_CASE;
// 新文件名
String newFilename = RandomStringUtil.create(newFilenameLength, newFilenameType);
try {
File parentFile = new File(savePath);
// 保存文件夹不存在则创建
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 获取真实的文件名
String filename = file.getOriginalFilename();
assert filename != null;
// 文件后缀名
String suffix = filename.substring(filename.lastIndexOf("."));
InputStream inputStream = file.getInputStream();
OutputStream outputStream = new FileOutputStream(savePath + File.separator + newFilename + suffix);
// 复制文件至指定路径
IOUtils.copy(inputStream, outputStream);
// 清除缓存及关闭流
outputStream.flush();
outputStream.close();
inputStream.close();
// 返回文件路径
return savePath + File.separator + newFilename + suffix;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
controller层:
@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {
@PostMapping("test")
private String test(@RequestParam("file") MultipartFile file) {
ResultEntity resultEntity = new ResultEntity();
try {
// 文件的保存路径,这里以宝塔为例,需要文件夹的绝对路径,相对路径好像不太行
String saveFile = "/www/server/tomcat/webapps/images";
String result = UploadFileToService.upload(file, saveFile);
ResultEntityEvent.successEvent(resultEntity, "上传文件成功!", result, 1);
} catch (Exception e) {
ResultEntityEvent.exceptionEvent(e, resultEntity, "上传文件出错啦,请查看后端日志!");
e.printStackTrace();
}
return JsonTool.getJsonTool().toJson(resultEntity);
}
}
uni-app调用
uni.showLoading({
title: '文件上传中'
})
uni.chooseImage({
count: 1,
sizeType: 'compressed',
success: (res) => {
uni.uploadFile({
url: '接口路径',
filePath: res.tempFilePaths[0],
name: 'file',
success: (uploadFileRes) => {
uni.hideLoading();
console.log(uploadFileRes.data);
}
});
res.tempFilePaths.forEach(function(item) {
uni.downloadFile({
url: item
})
})
},
fail: (data) => {}
})
h5端调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
<script type="text/javascript" src="/layui/layui.js"></script>
</head>
<body>
<input type="file" id="file">
<div type="button" id="btn">上传文件</div>
</body>
<script>
// 如果不是用layui的话需要导入jquery.js
const $ = layui.jquery;
document.getElementById('btn').onclick = function () {
const file = $('#file').get(0).files[0];
console.log(file);
const form_data = new FormData();
form_data.append('file', file);
$.ajax({
url: '接口',
type: 'POST',
dataType: 'JSON',
data: form_data,
cache: false,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
},
error: function (res) {
console.log(res);
}
});
}
</script>
</html>