不需要配置虚拟路径,存的时候数据库里只存了图片的名称(随机重命名的形式),存在指定服务器上,取的时候也是根据图片名称从服务器上找到,并用OutputStream 读出来
前台页面(用的bootstrap):
html代码(可回显,回显的时候也是去后台根据路径查找到图片):
<form id="pic" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${userComplete.id}">
<div class="row">
<div class="col-xs-2">
<label class="control-label">营业执照:</label>
</div>
<div class="col-xs-4 updateP1">
<img src="${pageContext.request.contextPath}/corporation/showImages/${userComplete.businessLicense}"
id="businessLicense"
style="width: 150px;height: 150px; border:1px solid #989898;">
<input type="hidden" name="businessLicense" value="${userComplete.businessLicense}"/>
</div>
<div class="col-md-4">
<div class="container">
<div class="col-md-12">
<input type="file" name="file1" id="file1">
</div>
<input type="button" value="重新上传" onclick="doUpload1()">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-1 col-xs-offset-3">
<input type="submit" name="提交" class="btn btn-danger">
</div>
</div>
</form>
js:
<script>
//图片预览路径
function getObjectURL(file) {
var url = null;
if(window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if(window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if(window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
function doUpload1(){
var formd = new FormData($("#pic")[0]);
var imgurl = getObjectURL($("#file1")[0].files[0]);
$("#businessLicense").attr({
"src":imgurl
});
var url="${pageContext.request.contextPath}/corporation/sendFile1";
$.ajax({
type:"post",
url:url,
data:formd,
contentType:false,
processData:false,
dataType:"json",
success:function (data) {
if(null!=data && data.flag==true){
alert("上传成功!");
$("#pic input[name='businessLicense']").val(data.filename);
}
},error:function (data) {
alert(1);
alert(data.message);
}
});
}
$("#pic").submit(function () {
var data = $("#pic").serialize();
$.ajax({
url:"${pageContext.request.contextPath}/corporation/updateCorporation",
data:data,
type:"post",
datatype:"json",
success:function (data) {
if(data){
alert("修改成功!");
}
}
})
});
</script>
后台:
UserCompleteController:
package com.buba.witkey.controller;
import com.buba.witkey.pojo.UserComplete;
import com.buba.witkey.service.UserCompleteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("/corporation")
@Controller
public class UserCompleteController {
@Resource
private UserCompleteService userCompleteService;
@RequestMapping("/sendFile1")
@ResponseBody
public Map<String,Object> sendFile1(MultipartFile file1, HttpSession session){
Map<String,Object> map = new HashMap<>();
map.put("flag",true);
String realPath = session.getServletContext().getRealPath("/uploads/lisence");
File temp = new File(realPath);
if(!temp.exists()){
//如果不存在,就新建一个路径
temp.mkdir();
}
String filename = file1.getOriginalFilename();
//限制上传的文件必须是图片,通过后缀名的方式
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
if(!suffix.matches("^(?i)[(PNG)|(GIF)|(JPG)|(JPEG)]+$")){
map.put("flag",false);
map.put("message","请上传图片!");
return map;
}
//如果图片超过512M,返回false
if(file1.getSize()>512*1024*1024){
map.put("flag",false);
map.put("message","文件不支持>512KB!");
return map;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String format = sdf.format(new Date());
filename = filename.substring(0,filename.lastIndexOf("."))+"_"+format+filename.substring(filename.lastIndexOf("."));
File f = new File(realPath+File.separator+filename);
try {
file1.transferTo(f);
} catch (IOException e) {
e.printStackTrace();
map.put("flag",false);
map.put("message","上传失败,详细信息为:"+e.getMessage());
return map;
}
map.put("filename",filename);
return map;
}
@RequestMapping("/updateCorporation")
@ResponseBody
public boolean updateCorporation(UserComplete uc){
int ucs = userCompleteService.updateCorporation(uc);
if(ucs!=0){
return true;
}
return false;
}
@RequestMapping("/showImages/{image:.+}")
public void showImages(@PathVariable String image, HttpSession session, HttpServletResponse response){
System.out.println("图片名称为:"+image);
//获取存储图片的绝对路径
String realPath = session.getServletContext().getRealPath("/uploads/lisence");
File file = new File(realPath+File.separator+image);
try(FileInputStream fin = new FileInputStream(file);
OutputStream out = response.getOutputStream();
) {
byte[] buffer = new byte[1024];
int count = 0;
while ((count=fin.read(buffer))!=-1){
out.write(buffer,0,count);
out.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
又over了!再见大兄弟们!