Controller
PrintWriter printWriter = response.getWriter();
String fileName = file.getOriginalFilename();
String uploadpath = ResourceUtils.getURL("classpath:").getPath() + "static/images/partForImgCenter/source" + fileName;
try {
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(uploadpath)));
stream.write(file.getBytes());
printWriter.write("123");
printWriter.close();
stream.close();
}catch (Exception e)
{
e.printStackTrace();
}
js
function upload(obj){
var img = document.getElementById("....");
var file = obj.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
img.setAttribute("src", this.result);
};
var formData = new FormData();
formData.append('file',file);
$.ajax({
url:"${pageContext.request.contextPath}/ImageService/uploadImg",
type:"post",
data:formData,
dataType:"json",
async:false,
cache: false,
contentType: false,
processData: false,
});
}
html
<form action=""class="imageSmallContent" id="img_a1" mothod="post">
<img src="..." alt="代替input的图片" id="showImg" style="..; absolute;">
<input type="file" name="" id="" value="" onchange="upload(this)" style="width: 248px;height: 108px;opacity:0;"/>
</form>