private static final String suffixArray[] = {
"html",
"txt",
"css",
"js",
"jsp",
"exe"
};
/**
* 更新 用户头像。 接受的有openid
* /api/xcx/user/uploadimage
* @RequestParam("file") MultipartFile file,
* 这个接口2个地方 使用。
*/
@ResponseBody
@RequestMapping("/uploadimage")
public JSONObject uploadimage( @RequestParam("openid") String openid,
@RequestParam(value = "type", required = false) Integer type,
HttpServletRequest request)throws Exception {
JSONObject result = new JSONObject();
//获取文件需要上传到的路径
String webPath=request.getServletContext().getRealPath("");
System.out.println("openid:"+openid);//
System.out.println("type:"+type);//
XcxUser xcxUser =null;
if(type!=null){
//上传加修改头像 一起操作。 提交获取 user
xcxUser = xcxUserService.findByOpenid(openid);
}
String filePath= "/static/xcx_upload/xcx_user_head/"+ DateUtil.formatDate(new Date(), "yyyyMMdd")+"/";
FileUtil.makeDirs(webPath+filePath);
request.setCharacterEncoding("utf-8"); //设置编码
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
Iterator<String> iterator = req.getFileNames();
while (iterator.hasNext()) {
HashMap<String, Object> res = new HashMap<String, Object>();
MultipartFile file = req.getFile(iterator.next());
// 获取文件名
String fileNames = file.getOriginalFilename();
int split = fileNames.lastIndexOf(".");
//获取上传文件的后缀
String extName = fileNames.substring(split + 1, fileNames.length());
// 判断后缀名是否在允许的数组中
boolean isAllowed = Arrays.asList(suffixArray).contains(extName);
System.out.println(isAllowed);//这个名单可以说是 黑名单。
//false是不在名单中 true是在 名单中
if(isAllowed){
return null;
}
//申明UUID
String uuid = UUID.randomUUID().toString().replace("-", "");
//组成新的图片名称
String newName = uuid + "." + extName;
System.out.println(newName);
String destPath = webPath+filePath + newName;
//真正写到磁盘上
File file1 = new File(destPath);
OutputStream out = new FileOutputStream(file1);
out.write(file.getBytes());
res.put("url", destPath);
result.put("url", filePath+ newName);
//更新头像,
if(type!=null){
//判断 路径 有没有包含 xcx_upload 如果有就删除头像吧。
if(xcxUser.getHeadimgurl().contains("upload")){
FileUtil.deleteFile(webPath+xcxUser.getHeadimgurl());
}
//删除后 再更新。
xcxUser.setHeadimgurl(filePath+ newName);
xcxUserService.updateById(xcxUser);
}
out.close();
}
} catch (Exception e) {
}
return result;
}站长微信:xiaomao0055
站长QQ:14496453