/**form表单提交方式处理---文件流和其他普通参数*/
DiskFileItemFactory factory = new DiskFileItemFactory();// 创建磁盘工厂
factory.setSizeThreshold(10 * 1096);// 将文件保存在内存还是磁盘临时文件夹的默认临界值,值为10240,即10kb
ServletFileUpload upload = new ServletFileUpload(factory);// 创建处理工具
upload.setSizeMax(2048 * 1024 * 1024);// 服务器端可以接收的最大文件大小,-1表示无上限
//指定文件的保存路径
String uploadPath = request.getSession().getServletContext().getRealPath("/") + File.separator + "upload";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析请求的内容提取文件数据
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
if (fileName!=null&&fileName.length()>0) {
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message","文件上传成功!");
//同步user的图片信息
user.setImgURL("upload/"+fileName);
System.out.println("upload/"+fileName);
getService().getCustomMadeManager().update(user);
}
}else {
if (item.getFieldName().equals("imagedata")) {//如果名称是这个
String imagefile = item.getString();//获取名称对应的值
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
/**AJAX提交方式-----处理Base64转码*/
BASE64Decoder decoder = new BASE64Decoder();
try {
//去掉头data:image/jpeg;base64,
if (imagefile!=null&&imagefile.length()>0) {
String imagebasefile = imagefile.substring(23);
// Base64解码
byte[] bytes = decoder.decodeBuffer(imagebasefile);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
//生成JPEG图片输出流,名字,保存路径
String filename = (UUID.randomUUID().toString()).replaceAll("-", "")+".jpg";
uploadPath =uploadPath+"/"+filename;
FileOutputStream out = new FileOutputStream(uploadPath);
//更新用户头像URL
out.write(bytes);
out.flush();
out.close();
user.setImgURL("upload/"+filename);
getService().getCustomMadeManager().update(user);
}
} catch (Exception e) {
e.printStackTrace();
}