HTML:
<form method="POST" enctype="multipart/form-data" id="imgupload2">
<br>请选择图片:<input id="imgfile2" name="imgfile2" size="80" type="file"><input name="upload"type="button" value="开始导入2" οnclick="checkform2();"/>
</form>
JS:
$('#imgupload2').ajaxSubmit({
url:"upload/imgImport2",
type: 'POST',
dataType: "json",
success:function(result){
console.log(result);
//$('#img2').attr("src",result.message);
},
error:function(result){
console.log(result);
}
});
控制层:
@RequestMapping(value = "/imgImport2")
@ResponseBody
protected JsonResult uploadXmInfo2(HttpServletRequest req,HttpServletResponse res) throws Exception {
//将文件上传到本地磁盘目录下
String updoadFilePath = req.getServletContext().getRealPath("")+ "upload";
System.out.println("updoadFilePath:"+updoadFilePath);
File updoadDir = new File(updoadFilePath);
if (!updoadDir.exists()) {
updoadDir.mkdirs();
}
// 转型为MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
// 获得文件:
MultipartFile file = multipartRequest.getFile("imgfile2");
//获取文件名
String filename = file.getOriginalFilename();
//获取文件路径
String fullname = updoadFilePath + File.separator + filename;
System.out.println("fullname"+fullname);
File targetFile = new File(fullname);
if (targetFile.exists()) {
targetFile.delete();
}
targetFile.createNewFile();//
int rtnInt = FileUtil.CopyFile(file, fullname);
if(rtnInt!=0){
return new JsonResult(2,"图片上传失败");
}
uploadService.file2db(fullname);//将全路径保存在数据库
return new JsonResult(1,"成功");
}
============================保存图片完成=======================
============================显示图片==========================
自己本打算传递绝对路径到前端,让浏览器自己找到图片,但是不可以:Not allowed to load local resource: file:///C:/apache-tomcat- 8.5.6/webapps/MyLab/upload/2.png
所以采用下面的方式:
html:
图片2:<img src="<%=basePath%>/upload/showImage" id="img2" class='file-preview-image' width="100px" height="100px">
控制层(将图片以流的方式读出然后写入到img):
/**
* 显示图片
* @param re
* @param response
* @param pic_addr
*/
@RequestMapping(value = "/showImage")
public void showImage(HttpServletRequest re,HttpServletResponse response,String pic_addr){//pic_addr:图片路径(d:\\upload\a.jpg)
//response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/*");
FileInputStream fis = null;
OutputStream os = null;
try{
//fis = new FileInputStream(re.getSession().getServletContext().getRealPath("/res/fileUpload")+"/"+pic_addr);
//在这里我直接用了一个已经写好的路径
fis = new FileInputStream("C:\\apache-tomcat-8.5.6\\webapps\\MyLab\\upload\\2.png");
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024*8];
while ( (count = fis.read(buffer)) != -1 ){
os.write(buffer, 0, count);
os.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally {
try {
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}