JavaWeb上传头像
最近工作中遇到需要维护个人信息,包括头像信息,再次记录,方便以后使用
前端:
<img id="expert_img" alt="100x100" src="img/profile.png" width="200" height="200">
<div class="caption">
<a href="#" data-type="text" data-pk="1"
class="editable editable-click inputText"
style="margin-bottom: 10px;"> </a>
</div>
<div class="span12" style="margin-top: 10px; text-align: center; font-size: 18px;">
<input type="file" class="hide" id="uploadfile" name="upfile"class="" />
<a class="span12"href="javascript:openSelectFile();">添加附件</a></div>
js:
//上传文件
function openSelectFile(){
$("#uploadfile").trigger("click");//出发shi'jian
}
$('#uploadfile').fileupload({
dataType: 'json',
url:'admin/uploadImage',
formData:{businessType:"expert"},
autoUpload:true,
add: function (e, data) {
var fileType = data.files[0].name.split('.').pop();
var acceptFileTypes = /jpg|jpeg|png$/i;
if (!acceptFileTypes.test(fileType)) {
toastr.warning("不支持的文件类型");
return ;
}
var size = data.files[0].size;
size = (size/1024).toFixed(2);//文件大小单位kb
var maxFileSize = 10*1024;//最大允许文件大小单位kb
if(size>maxFileSize){
toastr.warning("文件大小:"+size+"KB,超过最大限制:"+maxFileSize+"KB");
return ;
}
data.submit();
},
fail:function (e, data) {
toastr.warning("附件上传失败,请重试或者联系管理员!");
},
done: function (e, data) {
//上传成功,把保存路径返回
$('#expert_img').attr('src','admin/images/'+data._response.result.url);
$('#expert_img_id').val(data._response.result.url);
}
});
后端:
/**
* 图片上传
* @param request
* @param response
* @return
*/
@RequestMapping(value="/admin/uploadImage",method=RequestMethod.POST)
@ResponseBody
public String uploadImage(@RequestParam("upfile") MultipartFile file,HttpServletRequest request){
JSONObject ret = new JSONObject();
JSONObject result = new JSONObject();
if (request.getSession().getAttribute("ADMIN-USER-INFO") == null) {
ret.put("code", "-2");
ret.put("msg", "你尚未登陆,请先登录!");
return ret.toJSONString();
}
try {
if(!file.isEmpty()){
int typeIndex = file.getOriginalFilename().lastIndexOf(".");
String name = file.getOriginalFilename();
String type = "" ;
if(typeIndex>0){
name = file.getOriginalFilename().substring(0,typeIndex);
type = file.getOriginalFilename().substring(typeIndex+1);
}
String dateDir = sf2.format(new Date());
String id = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
File dir = new File(uploadFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File destFile = new File(
uploadFileDir + File.separator +request.getParameter("businessType")+ File.separator + dateDir + File.separator + id);
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
result.put("id", id);
result.put("code", "1");
result.put("state", "SUCCESS");
result.put("url", request.getParameter("businessType")+"/"+dateDir+"/"+ id+"/"+type);
result.put("msg", "文件上传成功!");
}else{
result.put("code", "-1");
result.put("msg", "请选择需要上传的文件!");
}
} catch (Exception e) {
result.put("code", "-1");
result.put("msg", "上传文件异常,请重试或者联系管理员!");
}
return result.toJSONString();
}
@RequestMapping("/admin/images/{buinessType}/{dateDir}/{id}/{type}")
public ResponseEntity<byte[]> fileDownLoad(HttpServletRequest request,@PathVariable String buinessType, @PathVariable String dateDir, @PathVariable String id, @PathVariable String type) throws Exception {
File file = new File(uploadFileDir + File.separator + buinessType + File.separator
+ dateDir + File.separator + id);
InputStream in=new FileInputStream(file);
HttpHeaders headers=new HttpHeaders();//设置响应头
headers.add("Content-type","image/"+type);
// headers.add("Content-Disposition", "attachment;filename="+id);
HttpStatus statusCode = HttpStatus.OK;
byte[] body=null;
body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
in.read(body);
in.close();
ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
说明: $('#expert_img').attr('src','admin/images/'+data._response.result.url);
@RequestMapping("/admin/images/{buinessType}/{dateDir}/{id}/{type}")
data._response.result.url 存储的时相对路径,data._response.result.url 的内容={buinessType}/{dateDir}/{id}/{type} 图片将以流的方式正常显示