导入jquery.js这个使用了oootstrap前端框架,
html实现:
<a class="col-md-2 btn btn-base " id="uploadfile" style="display:none;" onclick="showFiles()" ><span class="glyphicon glyphicon-upload btn-base-padding"></span>上传</a>
<form enctype="multipart/form-data" style="display:none;" id="fileform" method="post" action="../uploadFile_project_img_infos.call">
<input type="file" name="uploadify" value="" onchange="submitfile()" id="myuploadFile" accept="image/*">
</form>
js实现:
//点击选择文件
function showFiles(){
$("#myuploadFile").click();
}
//上传文件
function submitfile(){
var value=$("#myuploadFile").val();
var types=value.split('.');
if(types[1]!='png'&&types[1]!='PNG'&&types[1]!='jpg'&&types[1]!='JPG'){
alert('请上传图片');
return ;
}
var formData = new FormData($( "#fileform" )[0]);
$.ajax({
url: '../uploadFile_project_img_infos.call' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if(data=='error'){
alert("上传失败");
}else{
var values=data.split('&');
$("#showfile").attr('src','../images/'+values[0]);
$("#i_img_url").val(values[0]);
alert("宽度:"+values[1]+"高度:"+values[2]);
}
},
error: function (res) {
alert(res);
}
});
}
通过按钮的点击事件触发<input type=''file" >的点击事件。选择文件通过onchange事件是点击之后直接上传。
/**
* 施工图上传图片
* @param file
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/uploadFile_project_img_infos.call")
public void uploadFile_project_img_infos(@RequestParam(value = "uploadify", required = false) MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws IOException{
//文件上传路径
String path = request.getServletContext().getRealPath("/images/");
//上传文件名
String filename = file.getOriginalFilename();
File filepath = new File(path, filename);
String names[]=filename.split("\\.");
if(names.length>=1){
String uuid = UUID.randomUUID().toString();
filename=uuid+"."+names[names.length-1];
}
//判断路径是否存在
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
try{
file.transferTo(new File(path+File.separator+filename));
//获取图片高度宽度
File picFile=new File(path+File.separator+filename);
BufferedImage bi=ImageIO.read(picFile);
int hg=bi.getHeight();
int wd=bi.getWidth();
JSONObject jo=new JSONObject();
//用&
response.getWriter().write(filename+"&"+wd+"&"+hg);
}catch(IOException e){
response.getWriter().write("error");
}
}
保存图片,并获取文件的宽高。