文件上传
package com.huawei.iop.service.worldCUP.userCluster; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.huawei.iop.common.Developer; import com.huawei.iop.common.IopConst; import com.huawei.iop.util.ConfigPropertiesUtil; import com.huawei.iop.util.IOHelperUtil; /** * 上传用户自定义群文件 * * @author * */ public class UploadGroupFileServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected final static Logger logger = Logger.getLogger("runtime"); @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String resultfilename = ""; // /* * String systemBasePath = "/home/iop/download/taskresults"; if * (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != * -1) { systemBasePath = "D:/"; } */ // 编写时间格式 Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String d = sdf.format(date); d = d.substring(0, 6); // 獲取當前時間的年月 SimpleDateFormat df = new SimpleDateFormat("yyyyMM"); String dateTime = df.format(date); // 确定文件路径 String resultPathFromConf = ConfigPropertiesUtil.readValue("uploadPath") + dateTime;// download/resultgroups String tempPath = null; if (StringUtils.isEmpty(resultPathFromConf)) { tempPath = "/home/iop/download/definedGroupUpload/" + dateTime; File tmpFile = new File(tempPath); if (!tmpFile.exists()) { boolean b = tmpFile.mkdirs(); if (b) { logger.info("tmpFile.mkdirs():" + b); } } resultPathFromConf = tempPath; } JSONObject object = new JSONObject(); File dir = new File(resultPathFromConf); if (!dir.exists() || !dir.isDirectory()) { boolean b = dir.mkdir(); if (b) { logger.info("dir.mkdir():" + b); } } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(dir); factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> list = (List<FileItem>) upload.parseRequest(req); for (FileItem item : list) { String name = item.getFieldName(); // 表单信息不是是普通文本信息 if (!(item.isFormField())) { String value = item.getName(); int start = value.lastIndexOf("\\"); String filename = value.substring(start + 1); req.setAttribute(name, filename); // 前台判断文件是否已上传过,若传过,则提示是否再次上传,确定再次上传提示用户覆盖先前文件 File file = new File(dir, filename); if (file.exists() && file.canRead() && file.canWrite()) { Developer.info("UploadGroupFileServlet.doPost()", "File exists," + "path=" + dir + "filename=" + filename); logger.error("UploadGroupFileServlet.doPost():File exists," + "path=" + dir + "filename=" + filename); } d = sdf.format(date); filename = "Upload" + d.substring(0, 14) + filename; resultfilename = filename; OutputStream out = null; InputStream in = null; try { in = item.getInputStream(); out = new FileOutputStream(new File(dir, filename)); int size = in.available(); if (size != 0) { int length = 0; byte[] buf = new byte[1024]; // 如文件存在且不为空,则备份到/home/iopdevelop/tempfiles目录下 if (file.exists() && file.canRead() && file.canWrite()) { OutputStream obu = null; InputStream ibu = null; File BACKUPPATH = null; String BACKUPFILENAME = null; Developer.info("UploadGroupFileServlet.doPost()", "begin to write file" + "path=" + dir + "filename=" + filename); logger.error("UploadGroupFileServlet.doPost():begin to write file" + "path=" + dir + "filename=" + filename); BACKUPPATH = new File(resultPathFromConf); BACKUPFILENAME = filename + System.currentTimeMillis(); try { obu = new FileOutputStream(new File(BACKUPPATH, BACKUPFILENAME));// backup // files ibu = item.getInputStream(); while ((length = ibu.read(buf)) != -1) { obu.write(buf, 0, length); } } catch (Exception e) { logger.info("obu is failed"); e.printStackTrace(); } finally { if (null != ibu) { IOHelperUtil.close(ibu); } if (null != obu) { IOHelperUtil.close(obu); } } Developer.info("UploadGroupFileServlet.doPost()", "backup File" + "path=" + BACKUPPATH + "filename=" + BACKUPFILENAME); logger.info("UploadGroupFileServlet.doPost(), backup File" + "path=" + BACKUPPATH + "filename=" + BACKUPFILENAME); } while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } object.put("statusCode", IopConst.IOP_RUN_SUCCESS); Developer.info("UploadGroupFileServlet.doPost()", "the request is" + req); logger.info("UploadGroupFileServlet.doPost(), the request is" + req); Developer.info("IO closed", "UploadGroupFileServlet.doPost()"); logger.info("IO closed, UploadGroupFileServlet.doPost()"); } else { logger.info("in.available() = 0"); } } catch (IOException e) { e.printStackTrace(); } finally { IOHelperUtil.close(in, out); } } } object.put("resultfilename", resultfilename); } catch (FileUploadException | JSONException e1) { e1.printStackTrace(); try { object.put("statusCode", IopConst.IOP_RUN_FAILSE);// 执行失败 logger.info("object.put(statusCode) IopConst.IOP_RUN_FAILSE"); } catch (JSONException e) { Developer.info("UploadGroupFileServlet executed but ERROR:" + e1, "UploadGroupFileServlet.doPost()"); logger.info("UploadGroupFileServlet executed but ERROR:" + e1 + "UploadGroupFileServlet.doPost(); IO closed, UploadGroupFileServlet.doPost()"); e.printStackTrace(); } finally { } } finally { ServletOutputStream writer = response.getOutputStream(); response.setContentType("text/html;charset=UTF-8"); writer.write(object.toString().getBytes("UTF-8")); writer.flush(); writer.close(); writer = null; } } }