public StringMap uploadPicture(HttpServletRequest request,
HttpServletResponse response)throws Exception{
StringMap map=new StringMap();
DiskFileItemFactory fac = new DiskFileItemFactory();
// 创建servlet文件上传组件
ServletFileUpload upload = new ServletFileUpload(fac);
List
fileInfoList = null;
try {
fileInfoList = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
}
Iterator
paramItem = fileInfoList.iterator();
Map
paraMap = new HashMap
();
while (paramItem.hasNext()) { //获取域中传入的普通参数
FileItem item = paramItem.next();
if (item.isFormField()){
String filedName = item.getFieldName();
String value = "";
try {
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
paraMap.put(filedName, value);
}
}
InetAddress addr = InetAddress.getLocalHost();
String localIp=addr.getHostAddress().toString();//获得本机IP
String pictureUrl="";
Iterator
fileItem = fileInfoList.iterator(); String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "png"}; while (fileItem.hasNext()){ //获取域中传入的文件参数 FileItem item = fileItem.next(); if (!item.isFormField()) { String filename = item.getName(); //得到文件名 String fileExt = filename.substring(filename.lastIndexOf(".") + 1); //得到文件格式 boolean isPiceure=false; //上传的文件是否图片 int allowedExtCount = allowedExt.length; for (int i=0; i< allowedExtCount; i++) { if (allowedExt[i].toLowerCase().equals(fileExt.toLowerCase())) isPiceure=true; } if (isPiceure) { String[] s = filename.split("\\.", 2); String fileName = System.currentTimeMillis()+ "." + s[1]; //s[1]为文件后缀名,这里文件名设置为随机值 try { String tomcatPath = "../webapps/ROOT"; //找到tomcat目录 File uploadDirPath = new File(tomcatPath + "/upload"); if (!uploadDirPath.exists()) { uploadDirPath.mkdirs(); File uploadDirPath_tmp = new File(tomcatPath + "/upload"); if (!uploadDirPath_tmp.exists()) { uploadDirPath_tmp.mkdir(); } } String serverpath = "http://" + localIp + ":8080"; //设置要上传的服务器地址和端口号; pictureUrl = serverpath + "/upload/" + fileName; //设置全路径 File copyfile = new File(tomcatPath + "/upload/" + fileName); if (!copyfile.exists()) { item.write(copyfile); //FileCopyUtils来自org.springframework.util.FileCopyUtils } } catch (Exception e) { e.printStackTrace(); } map.set("msg","图片上传成功!"); map.set("pictureUrl",pictureUrl); } else{ map.set("msg","图片上传失败或图片格式不正确!"); return map; } }} return map; }
Iterator<FileItem>的使用,实现文件(图片)上传,限制图片格式,设置随机文件名
最新推荐文章于 2021-02-20 14:35:19 发布