Java Code Examples for org.apache.commons.fileupload.servlet.ServletFileUpload#isMultipartContent()

The following examples show how to use org.apache.commons.fileupload.servlet.ServletFileUpload#isMultipartContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WorkbenchRequest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Wrap a request with an object aware of the current repository and application defaults.
 *
 * @param repository currently connected repository
 * @param request    current request
 * @param defaults   application default parameter values
 * @throws RepositoryException if there is an issue retrieving the parameter map
 * @throws IOException         if there is an issue retrieving the parameter map
 * @throws FileUploadException if there is an issue retrieving the parameter map
 */
public WorkbenchRequest(Repository repository, HttpServletRequest request, Map<String, String> defaults)
		throws RepositoryException, IOException, FileUploadException {
	super(request);
	this.defaults = defaults;
	this.decoder = new ValueDecoder(repository,
			(repository == null) ? SimpleValueFactory.getInstance() : repository.getValueFactory());
	String url = request.getRequestURL().toString();
	if (ServletFileUpload.isMultipartContent(this)) {
		parameters = getMultipartParameterMap();
	} else if (request.getQueryString() == null && url.contains(";")) {
		parameters = getUrlParameterMap(url);
	}
}
 
Example 2
Source File: CheckerServlet.java    From ttt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void doCheck(RequestState state) throws ServletException, IOException {
    try {
        if (!ServletFileUpload.isMultipartContent(state.request))
            processQueryRequest(state);
        else
            processNonQueryRequest(state);
        processCheck(state);
        processResponse(state);
    } finally {
        state.reset();
    }
}
 
Example 3
Source File: ImportPlaylistController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping
protected String handlePost(RedirectAttributes redirectAttributes,
                            HttpServletRequest request
) {
    Map<String, Object> map = new HashMap<String, Object>();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;

                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName,
                            item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    redirectAttributes.addFlashAttribute("model", map);
    return "redirect:importPlaylist";
}
 
Example 4
Source File: ImportPlaylistController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;

                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName()));
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example 5
Source File: MultiReadHttpServletRequestWrapperFilter.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException,	ServletException {
    if (!ServletFileUpload.isMultipartContent((HttpServletRequest)request)) {
        chain.doFilter(new MultiReadHttpServletRequestWrapper((HttpServletRequest) request), response);
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 6
Source File: AvatarUploadController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example 7
Source File: AlbianMVCServlet.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean isMultipartRequest(HttpServletRequest request) {
    return ServletFileUpload.isMultipartContent(request);
}
 
Example 8
Source File: PropertiesFileUploadServlet.java    From pingid-api-playground with Apache License 2.0 4 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	if (ServletFileUpload.isMultipartContent(request)) {

		try {
			ServletFileUpload propertiesFile = new ServletFileUpload();
			FileItemIterator fii = propertiesFile.getItemIterator(request);

			while(fii.hasNext()) {
				FileItemStream item = fii.next();
				String name = item.getFieldName();
				InputStream is = item.openStream();
				
				if (item.isFormField()) {
					return;
					
				} else {

					if (is != null) {
						
						Properties props = new Properties();
						props.load(is);
						
						// Set the appropriate pingid.properties values to session
						HttpSession session = request.getSession(false);
						session.setAttribute("pingid_org_alias", props.getProperty("org_alias"));
						session.setAttribute("pingid_token", props.getProperty("token"));
						session.setAttribute("pingid_use_base64_key", props.getProperty("use_base64_key"));
						session.setAttribute("pingid_url", props.getProperty("idp_url"));

						// Set the results of the action to the request attributes
						request.setAttribute("status", "OK");
						request.setAttribute("statusMessage", "Successfully imported pingid.properties");
						
						RequestDispatcher requestDispatcher;
						requestDispatcher = request.getRequestDispatcher("/index.jsp");
						requestDispatcher.forward(request, response);
					}
					return;					
				}
			}
		} catch (FileUploadException ex) {

			throw new ServletException(ex.getMessage());
		}

	} else {
           return;					
	}
}
 
Example 9
Source File: HeritFormBasedFileUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
    * 파일을 Upload 처리한다.
    *
    * @param request
    * @param where
    * @param maxFileSize
    * @return
    * @throws Exception
    */
   public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxFileSize);	// SizeLimitExceededException

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            ////System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
        } else {
            ////System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

            if ("".equals(item.getName())) {
        	continue;
            }

            // Process the input stream
            HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

            String tmp = item.getName();

            if (tmp.lastIndexOf("\\") >= 0) {
        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFileName(tmp);
            vo.setContentType(item.getContentType());
            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());

            if (tmp.lastIndexOf(".") >= 0) {
        	 vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
            }

            long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

            vo.setSize(size);

            list.add(vo);
        }
    }
} else {
    throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}

return list;
   }
 
Example 10
Source File: HeritFormBasedFileUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
    * 파일을 Upload 처리한다.
    *
    * @param request
    * @param where
    * @param maxFileSize
    * @return
    * @throws Exception
    */
   public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxFileSize);	// SizeLimitExceededException

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            ////System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
        } else {
            ////System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

            if ("".equals(item.getName())) {
        	continue;
            }

            // Process the input stream
            HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

            String tmp = item.getName();

            if (tmp.lastIndexOf("\\") >= 0) {
        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFileName(tmp);
            vo.setContentType(item.getContentType());
            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());

            if (tmp.lastIndexOf(".") >= 0) {
        	 vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
            }

            long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

            vo.setSize(size);

            list.add(vo);
        }
    }
} else {
    throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}

return list;
   }
 
Example 11
Source File: ImportDocRIS.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);      
    String ParentId=ListFields.get("CurrFold");    
    String RISType=ListFields.get("RISType");    
    PDDocsRIS D=new PDDocsRIS(SParent.getSessOPD(Req), RISType);
    D.ImportFileRIS(ParentId, FileData);    
    out.println(UpFileStatus.SetResultOk(Req, ""));
    FileData.close();
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 12
Source File: ImpElemF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField())
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        break;
        }
    }        
DriverGeneric PDSession=SParent.getSessOPD(Req);       
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(FileData);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject;
ObjPD Obj2Build;
int Tot=0;
for (int i=0; i<OPDObjectList.getLength(); i++)
    {
    OPDObject = OPDObjectList.item(i);
    Obj2Build=PDSession.BuildObj(OPDObject);
    Obj2Build.ProcesXMLNode(OPDObject);
    Tot++;
    }
DB.reset();    
out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot));
FileData.close();
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 13
Source File: AttachmentServlet.java    From swellrt with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
  // Process only multipart requests.
  if (ServletFileUpload.isMultipartContent(request)) {
    // Create a factory for disk-based file items.
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler.
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request.
    try {
      @SuppressWarnings("unchecked")
      List<FileItem> items = upload.parseRequest(request);
      AttachmentId id = null;
      String waveRefStr = null;
      FileItem fileItem = null;
      for (FileItem item : items) {
        // Process only file upload - discard other form item types.
        if (item.isFormField()) {
          if (item.getFieldName().equals("attachmentId")) {
            id = AttachmentId.deserialise(item.getString());
          }
          if (item.getFieldName().equals("waveRef")) {
            waveRefStr = item.getString();
          }
        } else {
          fileItem = item;
        }
      }

      if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
        return;
      }
      if (waveRefStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
        return;
      }

      WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
      ParticipantId user = sessionManager.getLoggedInUser(request);
      boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
      if (!isAuthorized) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      String fileName = fileItem.getName();
      // Get only the file name not whole path.
      if (fileName != null) {
        fileName = FilenameUtils.getName(fileName);
        service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
        response.setStatus(HttpServletResponse.SC_CREATED);
        String msg =
            String.format("The file with name: %s and id: %s was created successfully.",
                fileName, id);
        LOG.fine(msg);
        response.getWriter().print("OK");
        response.flushBuffer();
      }
    } catch (Exception e) {
      LOG.severe("Upload error", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "An error occurred while upload the file : " + e.getMessage());
    }
  } else {
    LOG.severe("Request contents type is not supported by the servlet.");
    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        "Request contents type is not supported by the servlet.");
  }
}
 
Example 14
Source File: FileUploadUtils.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
public static final HashMap UploadFile(HttpServletRequest request, HttpServletResponse response, String filepaths) throws Exception {
    HashMap params = new HashMap();
    String pathType = "images";
    if (!(filepaths.equals("")))
        pathType = filepaths;
    String readPath = "";
    String contextPath = "";
    if ((readPath == null) || (readPath.equals("")))
        readPath = request.getSession().getServletContext().getRealPath("");

    if ((contextPath == null) || (contextPath.equals("")))
        contextPath = request.getContextPath();

    String savePhotoPath = mkdirFile(readPath, pathType, true);
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setSizeThreshold(1024000);
        ServletFileUpload sfu = new ServletFileUpload(dff);
        List fileItems = sfu.parseRequest(request);
        sfu.setFileSizeMax(5000000L);
        sfu.setSizeMax(10000000L);
        sfu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = new String(item.getString().getBytes(
                        "ISO8859-1"), "utf-8");
                params.put(name, value);
            } else if ((item.getSize() > 0L) &&
                    (item.getName() != null)) {
                File fullFile = new File(item.getName());
                File fileOnServer = new File(savePhotoPath,
                        fullFile.getName());
                item.write(fileOnServer);
                String fileName2 = fileOnServer.getName();
                String fileType = fileName2.substring(fileName2
                        .lastIndexOf("."));
                String filepath = savePhotoPath + "/" +
                        new Date().getTime() + fileType;
                File newFile = new File(filepath);
                fileOnServer.renameTo(newFile);
                String returnString = filepath.substring(readPath
                        .length());
                params.put(item.getFieldName(), request.getRequestURL().toString().replace(request.getRequestURI(), "") + contextPath +
                        returnString);
            }
        }
    }

    return params;
}
 
Example 15
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
 * 上传验证,并初始化文件目录
 * 
 * @param request
 */
private String validateFields(HttpServletRequest request) {
	String errorInfo = "true";
	// boolean errorFlag = true;
	// 获取内容类型
	String contentType = request.getContentType();
	int contentLength = request.getContentLength();
	// 文件保存目录路径
	savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";
	// 文件保存目录URL
	saveUrl = request.getContextPath() + "/" + basePath + "/";
	File uploadDir = new File(savePath);
	if (contentType == null || !contentType.startsWith("multipart")) {
		// TODO
		System.out.println("请求不包含multipart/form-data流");
		errorInfo = "请求不包含multipart/form-data流";
	} else if (maxSize < contentLength) {
		// TODO
		System.out.println("上传文件大小超出文件最大大小");
		errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";
	} else if (!ServletFileUpload.isMultipartContent(request)) {
		// TODO
		errorInfo = "请选择文件";
	} else if (!uploadDir.isDirectory()) {// 检查目录
		// TODO
		errorInfo = "上传目录[" + savePath + "]不存在";
	} else if (!uploadDir.canWrite()) {
		// TODO
		errorInfo = "上传目录[" + savePath + "]没有写权限";
	} else if (!extMap.containsKey(dirName)) {
		// TODO
		errorInfo = "目录名不正确";
	} else {
		// .../basePath/dirName/
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		// .../basePath/dirName/yyyyMMdd/
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// 获取上传临时路径
		tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
		File file = new File(tempPath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	return errorInfo;
}
 
Example 16
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
	 * 处理上传内容
	 * 
	 * @param request
	 * @param maxSize
	 * @return
	 */
//	@SuppressWarnings("unchecked")
	private Map<String, Object> initFields(HttpServletRequest request) {

		// 存储表单字段和非表单字段
		Map<String, Object> map = new HashMap<String, Object>();

		// 第一步:判断request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 第二步:解析request
		if (isMultipart) {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 阀值,超过这个值才会写到临时目录,否则在内存中
			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(tempPath));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			upload.setHeaderEncoding("UTF-8");

			// 最大上传限制
			upload.setSizeMax(maxSize);

			/* FileItem */
			List<FileItem> items = null;
			// Parse the request
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 第3步:处理uploaded items
			if (items != null && items.size() > 0) {
				Iterator<FileItem> iter = items.iterator();
				// 文件域对象
				List<FileItem> list = new ArrayList<FileItem>();
				// 表单字段
				Map<String, String> fields = new HashMap<String, String>();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value = item.getString();
						fields.put(name, value);
					} else { // 文件域表单元素
						list.add(item);
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		}
		return map;
	}
 
Example 17
Source File: WebdavController.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Uploads a file to a WebDAV server
 * @param request the request
 * @return the uploaded item
 * @throws IOException if there is any error reading the content of the file
 * @throws WebDavException if there is any error uploading the file to the WebDAV server
 * @throws InvalidParametersException if there is any error parsing the request
 */
@PostMapping("/upload")
public ResultOne<WebDavItem> uploadItem(HttpServletRequest request) throws IOException, WebDavException,
    InvalidParametersException {
    if (ServletFileUpload.isMultipartContent(request)) {
        ResultOne<WebDavItem> result = new ResultOne<>();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String siteId = null;
            String profileId = null;
            String path = null;
            if (!iterator.hasNext()) {
                throw new InvalidParametersException("Request body is empty");
            }
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                try(InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        switch (name) {
                            case REQUEST_PARAM_SITEID:
                                siteId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PROFILE_ID:
                                profileId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PATH:
                                path = Streams.asString(stream);
                            default:
                                // Unknown parameter, just skip it...
                        }
                    } else {
                        String filename = item.getName();
                        if (StringUtils.isNotEmpty(filename)) {
                            filename = FilenameUtils.getName(filename);
                        }
                        result.setEntity(RESULT_KEY_ITEM,
                            webDavService.upload(siteId, profileId, path, filename, stream));
                        result.setResponse(ApiResponse.OK);
                    }
                }
            }
            return result;
        } catch (FileUploadException e) {
            throw new InvalidParametersException("The request body is invalid");
        }
    } else {
        throw new InvalidParametersException("The request is not multipart");
    }
}
 
Example 18
Source File: AddDocAdv.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean AddDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException
{
String FileName=null;
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }
String Acept=(String) ListFields.get("BOk");
if (Acept==null || Acept.length()==0)
    return(false);
DriverGeneric PDSession=SParent.getSessOPD(Req);
String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
PDDocs Doc;
if (DType==null)
    Doc = new PDDocs(PDSession);
else
    Doc = new PDDocs(PDSession, DType);
Record Rec=Doc.getRecSum();
Rec.initList();
Attribute Attr=Rec.nextAttr();
while (Attr!=null)
    {
    if (!List.contains(Attr.getName()))
        {
        String Val=(String) ListFields.get(Attr.getName());
        if (Attr.getType()==Attribute.tBOOLEAN)
            {
            if(Val == null)
                Attr.setValue(false);
            else
                Attr.setValue(true);
            }
        else if(Val != null)
            {
            SParent.FillAttr(Req, Attr, Val, false);
            }
        }
    Attr=Rec.nextAttr();
    }
Doc.assignValues(Rec);
Doc.setParentId(getActFolderId(Req));
String RefFile=(String) ListFields.get(PDDocs.fNAME+"_");
if (RefFile!=null && RefFile.length()!=0)
    {
    Doc.setFile(RefFile);
    }
else
    {
    Doc.setName(FileName);
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    }
Doc.insert();
return(true);
}
 
Example 19
Source File: AttachmentServlet.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
  // Process only multipart requests.
  if (ServletFileUpload.isMultipartContent(request)) {
    // Create a factory for disk-based file items.
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler.
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request.
    try {
      @SuppressWarnings("unchecked")
      List<FileItem> items = upload.parseRequest(request);
      AttachmentId id = null;
      String waveRefStr = null;
      FileItem fileItem = null;
      for (FileItem item : items) {
        // Process only file upload - discard other form item types.
        if (item.isFormField()) {
          if (item.getFieldName().equals("attachmentId")) {
            id = AttachmentId.deserialise(item.getString());
          }
          if (item.getFieldName().equals("waveRef")) {
            waveRefStr = item.getString();
          }
        } else {
          fileItem = item;
        }
      }

      if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
        return;
      }
      if (waveRefStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
        return;
      }

      WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
      ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
      boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
      if (!isAuthorized) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      // Get only the file name not whole path.
      if (fileItem != null && fileItem.getName()  != null) {
        String fileName = FilenameUtils.getName(fileItem.getName());
        service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
        response.setStatus(HttpServletResponse.SC_CREATED);
        String msg =
            String.format("The file with name: %s and id: %s was created successfully.",
                fileName, id);
        LOG.fine(msg);
        response.getWriter().print("OK");
        response.flushBuffer();
      }
    } catch (Exception e) {
      LOG.severe("Upload error", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "An error occurred while upload the file : " + e.getMessage());
    }
  } else {
    LOG.severe("Request contents type is not supported by the servlet.");
    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        "Request contents type is not supported by the servlet.");
  }
}
 
Example 20
Source File: MultipartUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Check if the given HTTP request has multipart content
 * 
 * @param request
 *            the HTTP request
 * @return true if it has multipart content, false otherwise
 */
public static boolean isMultipart( HttpServletRequest request )
{
    return ServletFileUpload.isMultipartContent( request );
}