package zz.homework.util;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
* @author Administrator
* 上传文件工具
*/
public class UpLoadUtils {
@SuppressWarnings("unchecked")
public static Map<String,String> upload(HttpServletRequest req){
// 创建一个Map集合 用来存放所有的参数数据
HashMap<String,String> hashMap = new HashMap<String,String>();
try {
//创建工具对象
DiskFileItemFactory dff = new DiskFileItemFactory();
//创建上传工具
ServletFileUpload up = new ServletFileUpload(dff);
//限制上传文件的大小
up.setFileSizeMax(1024*1024);
// 解析请求中的二进制数据 返回一个List集合
List<FileItem> list = up.parseRequest(req);
for (FileItem fi : list) {
if(fi.isFormField()){
//普通字段
hashMap.put(fi.getFieldName(),fi.getString("utf-8"));
}else{
//限制文件类型为需要的
String ct = fi.getContentType();
if(!ct.startsWith("image/")){
throw new Exception("请选择图片上传!!");
}
//获取到后缀名称
String exName = FilenameUtils.getExtension(fi.getName());
//当前时间毫秒数作为随机数
String readomName = ""+System.currentTimeMillis();
//设置文件名
String realPath = req.getServletContext().getRealPath("/headImg");
//将文件名的反斜杠转换为正斜杠
realPath = realPath.replace("\\","/");
//命名
fi.write(new File(realPath+"/"+readomName+"."+exName));
//执行DAO操作 保存到数据库
hashMap.put("headImg","headImg/"+readomName+"."+exName);
}
}
//提示
req.setAttribute("msg","上传成功!!");
} catch (FileSizeLimitExceededException e) {
req.setAttribute("msg","文件大小请勿超过1M!!");
} catch (Exception e) {
req.setAttribute("msg","注册失败!!");
}
return hashMap;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/75236.html