1、创建一个HTML表单:
<form enctype="multipart/form-data" id="imgForm">
<input type="file" name="file">
<input type="button" value="upload" id="uploadBtn">
</form>
<img src="" id="myspan"/>
2、编写AJAX请求:
注意:这里不需要设置请求头content-type类型,send括号里提交的是整个表单数据!!
window.onload=function () {
document.getElementById("uploadBtn").onclick=function () {
//1.创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//2.注册回调函数
xhr.onreadystatechange = function (){
if (this.readyState == 4) {
if (this.status == 200) {
//后端成功返回的话,在img标签内回显图片,这里向后端再次发送请求
document.getElementById("myspan").src = "/download?name="+this.responseText
}else {
alert(this.status)
}
}
}
//3.开启通道
xhr.open("POST","/upload",true)
//4.发送请求
//xhr.setRequestHeader("Content-Type","multipart/form-data");
var form = document.getElementById("imgForm");
var data = new FormData(form) ;
xhr.send(data);
}
}
3、后端代码
注意:文件上传返回的是字符串,要加入@ResponseBody注解
@Controller
public class BasicController {
//图片的保存路径
String basePath = "E:\\img\\";
//文件上传
@PostMapping("/upload")
@ResponseBody
public String upload(MultipartFile file){
//file是一个临时文件,需要转存到指定的位置,否则本次请求完成后临时文件会删除
//原始文件名
String originalFilename = file.getOriginalFilename();
//文件后缀.jpg
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
String fileName = UUID.randomUUID().toString()+suffix;
//创建一个目录对象
File dir = new File(basePath);
//判断当前目录是否存在
if (!dir.exists()) {
dir.mkdirs();
}
try {
//将临时文件转存到指定位置
file.transferTo(new File(basePath+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
//文件下载
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try {
//输入流,通过输入流读取文件内容
FileInputStream fileInputStream = new FileInputStream(new File(basePath,name));
//输出流,通过输出流将文件写回浏览器,在浏览器展示图片
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
byte[] bytes = new byte[1024];
int readCount = 0;
while ((readCount= fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,readCount);
outputStream.flush();
}
//关闭资源
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}