html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-2.1.0.js"></script>
</head>
<body>
<form id="files">
<input type="file" name="file">
<input type="button" id="tijiao" value="提交">
<input type="button" value="删除">
<br>
<img src="" width="1000px" height="500px">
</form>
<script>
$(function (){
$("#tijiao").click(function () {
alert('提交成功');
var formData = new FormData($('#files')[0]);
$.ajax({
url:'shangchuan',
type:'post',
data: formData,//需要提交的数据,传入实例化的formdata对象,,此对象包含了要上传的文件
processData: false,
contentType:false,
});
})
var fd = new FormData(document.getElementsByTagName("form")[0]);
var photo = document.querySelector("input");
var img = document.querySelector("img");
photo.onchange = function (){
img.src = window.URL.createObjectURL(this.files[0]);
}
})
</script>
</body>
</html>
controller:
package com.example.uploadanimage.controller;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
public class Upload {
@PostMapping("/shangchuan")
public String shangchuan(MultipartFile file) throws Exception {
String originalFilename = file.getOriginalFilename();
System.out.println(originalFilename);
File file1 = new File("D:\\img",originalFilename);
file.transferTo(file1);
return "上传成功";
}
}
html页面:
页面回显效果图:
提交:
提交完成存入文件夹: