示例效果:
前端代码:
<html>
<head><title>上传文件示例</title></head>
<body>
<h2>方式一:普通表单上传</h2>
<form action="/admin/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="文件上传"/>
</form>
<h2>方式二:fetch异步上传</h2>
<input type="file" id="fileInput"/>
<script type="text/javascript">
const fileInput = document.getElementById('fileInput');
// 当文件被选中时上传文件
fileInput.addEventListener('change', function (e) {
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
fetch('/admin/upload', {
method: 'POST',
body: formData
}).then(response => response.json()) // 如果API返回JSON,解析它
.then(data => {
document.getElementById('fileInput').value = "";
alert(JSON.stringify(data));
}) // 处理解析后的数据
.catch(error => console.error('Error:', error)); // 处理错误
});
</script>
<h2>方式三:文件和文本一起提交</h2>
<input type="text" id="text"><br/>
<input type="file" id="file"/>
<input type="button" value="提交" onclick="submitForm()">
<script type="text/javascript">
function submitForm() {
const text = document.getElementById('text').value;
const file = document.getElementById('file').files[0];
const formData = new FormData();
formData.append('text', text);
formData.append('file', file);
fetch('/admin/upload', {
method: 'POST',
body: formData
}).then(response => response.json())
.then(data => {
alert(JSON.stringify(data));
});
}
</script>
</body>
</html>
后台代码
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "text", required = false) String text) {
//文件保存路径为在D盘下的upload文件夹,可以按照自己的习惯修改
String FILE_UPLOAD_PATH = "D:\\upload\\";
//如果目录不存在,则创建目录
Path path = Paths.get(FILE_UPLOAD_PATH);
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.isEmpty()) {
return "文件上传失败";
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
try {
//保存文件
byte[] bytes = file.getBytes();
Path filePath = Paths.get(FILE_UPLOAD_PATH + newFileName);
Files.write(filePath, bytes);
} catch (IOException e) {
e.printStackTrace();
}
var res = new JSONObject();
res.put("flag", true);
res.put("body", "上传成功");
res.put("text", text);
return res.toString();
}
此处仅演示如何实现简单的文件上传,实际环境中,还需做相应的身份认证,权限控制等。