1.jsp
<form class="form-inline" id="form1" enctype="multipart/form-data">
<div style="float:left; width: 140px;height: 194px;background-color : #fff;position:relative ;left:30px;top:20px; text-align: center;padding-top:80px">
<img src="" alt=""
style="width: 140px;height: 195px;position: absolute;top:0px;left:0px"
id="imgIdent" οnclick="uploudFileIdent('file')">
<input type="file" style="display: none" name="file" id="file" οnchange="uploadFile('imgIdent','file','form1','picture','${APP_PATH }')"/>
<button type="submit" class="btn btn-link"
style="margin: 0 auto;width: 100px;font-size: 16px;letter-spacing: 2px;"
οnclick="uploudFileIdent('file')">证件照</button>
</img>
</div>
</form>
2.js
/*上传图片-通用方法*/
function uploadFile(img_id,file_name,from_id,input_id,base_url){
var form=document.getElementById(from_id);
var fd =new FormData(form);
fd.append("fileName",file_name);
fd.append("oldUrl",$("#"+input_id).val());
$.ajax({
type: "POST",
data :fd,
url :base_url+"/uploadFile.action",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success :function(data){
//验证图片格式,并将图片回显
setImage(file_name,img_id);
//setImageCard1("cardid1_file","cardid1");
var backData = JSON.parse(data);
var url = backData.url;
/* 将返回的url放入指定的隐藏域中 */
// document.getElementById("idCard1").value=url;
$("#"+input_id).val(url);
}
});
}
function uploudFileIdent(obj){
$("#"+obj).click();
}
3.java
@RequestMapping("uploadFile")
@ResponseBody
public String uploadFile(HttpServletRequest request) throws IOException{
MultipartHttpServletRequest req=(MultipartHttpServletRequest) request;
String fileName=req.getParameter("fileName").toString();
String oldUrl=req.getParameter("oldUrl").toString();
//System.out.println("文件名称是:"+fileName+"原来的图片路径是:"+oldUrl);
MultipartFile file=req.getFile(fileName);
String orgName = file.getOriginalFilename();
String newOrgName = StringUtils.substringAfterLast(orgName, ".");
String newName = "";
byte[] bytes = new byte[10240];
bytes = file.getBytes();
long size = file.getSize();
if(size<10240 || size>1024000*24){
// setMsg("文件大小不符合规定,请上传大于10k、小于3MB的照片");
return null;
}
/*删除之前的文件*/
if(oldUrl.length()>5){
String deletePath="D:"+oldUrl.substring(5);
File deleteFile=new File(deletePath);
deleteFile.delete();
}
try {
// newName = getRandomString(5) + "." + newOrgName;
newName = getRandomString(16)+"."+newOrgName;
File file1 = new File("D:/BZXTWJ"+"\\csdnapi\\" +uniqueid+ "\\picture\\" + newName);
if (!file1.exists()) {
file1.mkdirs();
}
file.transferTo(file1);
} catch (Exception ex) {
return null;
}
Map map = new HashMap();
String url = "/file/BZXTWJ/csdnapi/"+uniqueid+ "/picture/" + newName;
map.put("url", url);
String jsonString = JSON.toJSONString(map);
return jsonString;
}