public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
Esempio n. 2
0
 /**
  * Add listener to fileItem which is going to be automatically destroyed when the servlet is
  * destroyed
  *
  * @param pipelineContext PipelineContext
  * @param fileItem FileItem
  */
 public static void deleteFileOnContextDestroyed(
     PipelineContext pipelineContext, final FileItem fileItem) {
   // Try to delete the file on exit and on session termination
   final ExternalContext externalContext =
       (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
   ExternalContext.Application application = externalContext.getApplication();
   if (application != null) {
     application.addListener(
         new ExternalContext.Application.ApplicationListener() {
           public void servletDestroyed() {
             deleteFileItem(fileItem, APPLICATION_SCOPE);
           }
         });
   } else {
     logger.debug(
         "No application object found so cannot register temporary file deletion upon session destruction: "
             + fileItem.getName());
   }
 }
Esempio n. 3
0
 /**
  * Add listener to fileItem which is going to be automatically destroyed on session destruction
  *
  * @param pipelineContext PipelineContext
  * @param fileItem FileItem
  */
 public static void deleteFileOnSessionTermination(
     PipelineContext pipelineContext, final FileItem fileItem) {
   // Try to delete the file on exit and on session termination
   final ExternalContext externalContext =
       (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
   final ExternalContext.Session session = externalContext.getSession(false);
   if (session != null) {
     session.addListener(
         new ExternalContext.Session.SessionListener() {
           public void sessionDestroyed() {
             deleteFileItem(fileItem, SESSION_SCOPE);
           }
         });
   } else {
     logger.debug(
         "No existing session found so cannot register temporary file deletion upon session destruction: "
             + fileItem.getName());
   }
 }
Esempio n. 4
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
      for (FileItem item : items) {
        if (item.isFormField()) {
          // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
          String fieldname = item.getFieldName();
          String fieldvalue = item.getString();
          // ... (do your job here)
        } else {
          // Process form file field (input type="file").
          String fieldname = item.getFieldName();
          String filename = FilenameUtils.getName(item.getName());
          InputStream filecontent = item.getInputStream();
          // ... (do your job here)
        }
      }
    } catch (FileUploadException e) {
      throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
  }
Esempio n. 5
0
  /**
   * 文件的上传服务
   *
   * @param request
   * @return
   * @throws FileUploadException
   * @throws IOException
   */
  public FileRepository uploadFile(HttpServletRequest request)
      throws FileUploadException, IOException {

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    FileRepository fileRepository = null;
    if (isMultipartContent) {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List<FileItem> items = upload.parseRequest(request);
      for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext(); ) {
        FileItem item = iterator.next();
        InputStream inputStream = item.getInputStream();
        // 获得文件名
        String fileName = item.getName();
        String fileExtension = FileUtil.getFileExtension(fileName);
        // 获得文件的Extension类型
        MimeTypeExtension mimeTypeExtension =
            mimeTypeExtensionService.findByMimeTypeExtensionName(fileExtension);
        fileRepository = new FileRepository();
        FixEntityUtil.fixEntity(fileRepository);
        String fileRepoId = fileRepository.getId();
        fileRepository.setMimeTypeExtensionName(fileExtension);
        if (mimeTypeExtension.getMimeType() != null) {
          fileRepository.setMimeTypeName(mimeTypeExtension.getMimeType().getMimeTypeName());
        }
        fileRepository.setFileName(fileName);
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String saveFilePath = Config.UPLOAD_FILE_PATH + "/" + datePath + "/";
        File file = new File(saveFilePath);
        if (!file.exists()) {
          file.mkdirs();
        }

        file = new File(saveFilePath + fileRepoId + ".xzsoft");
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int byteRead = 0;
        byte[] buffer = new byte[8192];
        while ((byteRead = inputStream.read(buffer, 0, 8192)) != -1) {
          out.write(buffer, 0, byteRead);
        }

        inputStream.close();
        // 将上传的文件变Base64加密过的字符串
        String content = Base64.encode(out.toByteArray());
        out.close();

        // 将加密过后的数据存储到硬盘中
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fileWriter);
        bw.write(content);
        bw.flush();
        fileWriter.flush();
        bw.close();
        fileWriter.close();
      }

    } else {
      throw new NotMultipartRequestException("上传的文件里面没有Multipart内容");
    }

    return fileRepository;
  }