Springboot 实现文件上传
1.html
<button type="button" οnclick="upload()" id="uploadBtn" class="a-upload mr10" ><i class="layui-icon"></i>上传文件 </button>
<a href="javascript:;" id="upload" class="a-upload mr10"><input type="file" name="file" id="file">选择文件</a>
2.js
function upload() {
var formData = new FormData();
formData.append("file",$('#file')[0].files[0])
$.ajax({
url: "填写后端的url",
mimeType:"multipart/form-data",
data: formData,
type: "Post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
if (result.code==0){
layer.msg("上传成功");
//推迟两秒刷新页面
setTimeout(function (){window.location.reload()}, 2000);
// window.location.reload(); //刷新页面
}
if(result.code==500){
layer.msg(result.msg);
}
console.log(result);
},
})
}
3.后端controller层代码
@PostMapping("fileUpload")
@ResponseBody
public AjaxResult fileUpload(@RequestParam("file") MultipartFile file){
// 获取文件名
String fileName = file.getOriginalFilename();
//判断是否为IE浏览器的文件名,IE浏览器下文件名会带有盘符信息
int unixSep = fileName.lastIndexOf('/');
// 检查windows样式的路径
int winSep = fileName.lastIndexOf('\\');
int pos = (Math.max(winSep, unixSep));
if (pos != -1) {
fileName = fileName.substring(pos + 1);
}
// 判断是否存在同名文件
if (existsFile(fileName)) {
return error("存在同名文件,请先删除原有文件再次上传");
}
//FILE_DIR 存放文件地址
File outFile = new File(FILE_DIR());
if (!outFile.exists()) {
outFile.mkdirs();
}
log.info("上传路径======"+FILE_DIR()+ fileName);
try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(FILE_DIR() + fileName)) {
StreamUtils.copy(in, out);
out.close();
in.close();
return success("文件上传成功");
} catch (IOException e) {
logger.error("文件上传失败", e);
return error("文件上传失败");
}
}