Java Code Examples for org.apache.commons.fileupload.disk.DiskFileItemFactory.setRepository()

The following are Jave code examples for showing how to use setRepository() of the org.apache.commons.fileupload.disk.DiskFileItemFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: iBase4J-Common   File: UploadUtil.java   View Source Code Vote up 8 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 2
Project: JAVA-   File: UploadUtil.java   View Source Code Vote up 8 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 3
Project: automat   File: UploadUtil.java   View Source Code Vote up 7 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 4
Project: mumu   File: UploadUtil.java   View Source Code Vote up 7 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 5
Project: iBase4J   File: UploadUtil.java   View Source Code Vote up 7 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 6
Project: mumu-core   File: UploadUtil.java   View Source Code Vote up 7 votes
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 7
Project: osframe   File: UploadUtil.java   View Source Code Vote up 7 votes
/** 获取所有文本域 */
public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 8
Project: struts2   File: JakartaMultiPartRequest.java   View Source Code Vote up 7 votes
protected DiskFileItemFactory createDiskFileItemFactory(String saveDir) {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    return fac;
}
 
Example 9
Project: xslweb   File: RequestSerializer.java   View Source Code Vote up 7 votes
private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException {
  List<FileItem> items = null;
  boolean isMultipart = ServletFileUpload.isMultipartContent(req);    
  if (isMultipart) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString());
    if (!reposDir.mkdirs()) {
      throw new XSLWebException(String.format("Could not create DiskFileItemFactory repository directory (%s)", reposDir.getAbsolutePath()));
    }
    factory.setRepository(reposDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize());
    items = upload.parseRequest(req);      
  }
  return items;
}
 
Example 10
Project: jawn   File: JawnServletContext.java   View Source Code Vote up 7 votes
/**
 * Gets the FileItemIterator of the input.
 * 
 * Can be used to process uploads in a streaming fashion. Check out:
 * http://commons.apache.org/fileupload/streaming.html
 * 
 * @return the FileItemIterator of the request or null if there was an
 *         error.
 */
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
    factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
    //README the file for tmpdir *MIGHT* need to go into Properties
    
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    if(encoding != null)
        upload.setHeaderEncoding(encoding);
    upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));
    
    try {
        List<FormItem> items = upload.parseRequest(request)
                .stream()
                .map(item -> new ApacheFileItemFormItem(item))
                .collect(Collectors.toList());
        return Optional.of(items);
    } catch (FileUploadException e) {
        //"Error while trying to process mulitpart file upload"
        //README: perhaps some logging
    }
    return Optional.empty();
}
 
Example 11
Project: drinkwater-java   File: FileUploadProcessor.java   View Source Code Vote up 6 votes
@Override
public void process(Exchange exchange) throws Exception {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ExchangeFileUpload upload = new ExchangeFileUpload(factory);

    java.util.List<FileItem> items = upload.parseExchange(exchange);

    if(items.size() >= 1){
        exchange.getIn().setBody(items.get(0).getInputStream());

        for (int i = 1; i < items.size(); i++) {
            exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream());
        }
    }
}
 
Example 12
Project: urule   File: FrameServletHandler.java   View Source Code Vote up 6 votes
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	boolean overwriteProject=true;
	List<FileItem> items = upload.parseRequest(req);
	if(items.size()==0){
		throw new ServletException("Upload file is invalid.");
	}
	for(FileItem item:items){
		String name=item.getFieldName();
		if(name.equals("overwriteProject")){
			String overwriteProjectStr=new String(item.get());
			overwriteProject=Boolean.valueOf(overwriteProjectStr);
		}else if(name.equals("file")){
			inputStream=item.getInputStream();
		}
	}
	repositoryService.importXml(inputStream,overwriteProject);
	IOUtils.closeQuietly(inputStream);
	resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
 
Example 13
Project: drinkwater-java   File: FileUploadProcessor.java   View Source Code Vote up 6 votes
@Override
public void process(Exchange exchange) throws Exception {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ExchangeFileUpload upload = new ExchangeFileUpload(factory);

    java.util.List<FileItem> items = upload.parseExchange(exchange);

    if(items.size() >= 1){
        exchange.getIn().setBody(items.get(0).getInputStream());

        for (int i = 1; i < items.size(); i++) {
            exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream());
        }
    }
}
 
Example 14
Project: Poseidon   File: PoseidonServlet.java   View Source Code Vote up 6 votes
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException {
    // If uploaded file size is more than 10KB, will be stored in disk
    DiskFileItemFactory factory = new DiskFileItemFactory();
    File repository = new File(FILE_UPLOAD_TMP_DIR);
    if (repository.exists()) {
        factory.setRepository(repository);
    }

    // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem
    // Apps also have to delete tmp file explicitly (if at all it went to disk)
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(httpRequest);
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    for (FileItem fileItem : fileItems) {
        String name = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            request.setAttribute(name, new String[] { fileItem.getString() });
        } else {
            request.setAttribute(name, fileItem);
        }
    }
}
 
Example 15
Project: bird   File: UploadImage.java   View Source Code Vote up 6 votes
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	try {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		factory.setRepository(tempPathFile);
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
		List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
		Iterator<FileItem> i = items.iterator();
		while (i.hasNext()) {
		    FileItem fi = (FileItem) i.next();
		    String fileName = fi.getName();
		    if (fileName != null) {
		     File fullFile = new File(fi.getName());
		     File savedFile = new File(uploadPath, fullFile.getName());
		     fi.write(savedFile);
		    }
		 }

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Project: metalcon   File: Server.java   View Source Code Vote up 6 votes
@Override
public void contextInitialized(ServletContextEvent arg0) {
	System.out.println("context initialized");
	this.start();

	final ServletContext context = arg0.getServletContext();
	context.setAttribute("server", this);

	// load status update types
	try {
		System.out.println("loading status update templates");
		StatusUpdateManager.loadStatusUpdateTemplates(
				context.getRealPath("/") + "WEB-INF/", this.config,
				this.graphDatabase);
		System.out.println("status update templates loaded");
	} catch (ParserConfigurationException | SAXException | IOException e) {
		System.err.println("failed to load status update templates!");
		e.printStackTrace();
	}

	final File tmpDir = (File) context
			.getAttribute("javax.servlet.context.tempdir");
	final DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(tmpDir);
	Create.setDiskFileItemFactory(factory);
}
 
Example 17
Project: OftenPorter   File: MultiPartParamSourceHandle.java   View Source Code Vote up 5 votes
public MultiPartParamSourceHandle(MultiPartOption multiPartOption, boolean dealNormalPut)
{
    this.multiPartOption = multiPartOption;
    this.dealNormalPut = dealNormalPut;
    factory = new DiskFileItemFactory();
    if (multiPartOption.tempDir != null)
    {
        factory.setRepository(new File(multiPartOption.tempDir));
    }
    factory.setSizeThreshold(multiPartOption.cacheSize);
}
 
Example 18
Project: DataStage   File: ExcelUploadService.java   View Source Code Vote up 5 votes
@Override
public void configFileUpload( DiskFileItemFactory fileItemFactory,
        ServletFileUpload servletFileUpload )
{
    fileItemFactory.setSizeThreshold( BYTE_M * 10 );
    fileItemFactory.setRepository( new File( "D:\\appUploads" ) );
    servletFileUpload.setFileSizeMax( BYTE_M * 100 );
}
 
Example 19
Project: grain   File: FileHttpFilter.java   View Source Code Vote up 5 votes
/**
 * 初始化缓存文件夹
 */
public FileHttpFilter() {
	tempPath = HttpConfig.PROJECT_PATH + "/" + HttpConfig.PROJECT_NAME + "_TEMP";
	if (HttpConfig.log != null) {
		HttpConfig.log.info("缓存文件路径为:" + tempPath);
	}
	File file = new File(tempPath);
	if (!file.exists()) {
		file.mkdirs();
	}
	diskFileItemFactory = new DiskFileItemFactory();
	diskFileItemFactory.setSizeThreshold(1024);
	diskFileItemFactory.setRepository(file);
}
 
Example 20
Project: PCloud_Server_v3   File: UploadAction.java   View Source Code Vote up 5 votes
@SuppressWarnings({ "unchecked" })
	private void receiveFile(HttpServletRequest request, OnFileReceiveListener listener) throws Exception{
		
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 临时文件夹路径
		String repositoryPath = ConfigManager.getManager().FILE_TEMP_PATH;
		// 设定临时文件夹为repositoryPath
		File fileTempFolder = new File(repositoryPath);
		if(!fileTempFolder.exists())fileTempFolder.mkdirs();
		factory.setRepository(fileTempFolder);

		// 设定上传文件的阈值,如果上传文件大于1M,就可能在repository
		// 所代 表的文件夹中产生临时文件,否则直接在内存中进行处理
		factory.setSizeThreshold(1024 * 1024);

		// 创建一个ServletFileUpload对象
		ServletFileUpload uploader = new ServletFileUpload(factory);

			// 调用uploader中的parseRequest方法,可以获得请求中的相关内容,
			// 即一个FileItem类型的ArrayList。FileItem是在
			// org.apache.commons.fileupload中定义的,它可以代表一个文件,
			// 也可以代表一个普通的form field
			ArrayList<FileItem> list = (ArrayList<FileItem>) uploader.parseRequest(request);
			for (FileItem fileItem : list){
				if (!fileItem.isFormField()){ // 如果是文件
					String fileName = fileItem.getName() + UUID.randomUUID();
					// 将其中包含的内容写到指定目录下名为fileName的文件中
					File file = new File(ConfigManager.getManager().FILE_SAVE_PATH + File.separator + fileName);
					file.createNewFile();
//					System.out.println(file.getPath());
					fileItem.write(file);
					
					listener.onFinished(MD5.getMD5CodeByFile(file),fileName,file.length());
					break;//一次请求只接受一个文件
				}
			}
	}
 
Example 21
Project: jw   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * @see http://www.oschina.net/code/snippet_698737_13402
 * @param request
 * @return
 * @throws IOException
 */
public static Map<String, Object> uploadFiles(HttpServlet servlet, HttpServletRequest request) {
    Map<String, Object> map = JwUtils.newHashMap();
    Map<String, String> fileMap = JwUtils.newHashMap();
    map.put("file", fileMap);

    DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工厂
    factory.setSizeThreshold(1024 * 1024 * 30);// 设置最大缓冲区为30M

    // 设置缓冲区目录
    String savePath = servlet.getServletContext().getRealPath("/WEB-INF/temp");
    factory.setRepository(new File(savePath));

    FileUpload upload = new FileUpload(factory);// 获得上传解析器
    upload.setHeaderEncoding("UTF-8");// 解决上传文件名乱码
    
    try {
        String targetFolderPath = servlet.getServletContext().getRealPath("/WEB-INF/" + ConfigUtils.getProperty("web.files.upload.folder"));
        File targetFolder = new File(targetFolderPath);// 目标文件夹
        if(!targetFolder.exists()) {
            targetFolder.mkdir();
        }
        
        List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));// 解析请求体
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判断是普通表单项还是文件上传项
                String name = fileItem.getFieldName();// 表单名
                String value = fileItem.getString("UTF-8");// 表单值
                map.put(name, value);
            } else {// 文件上传项
                String fileName = fileItem.getName();// 获取文件名
                if (StringUtils.isEmpty(fileName))// 判断是否上传了文件
                    continue;

                // 截取文件名
                int index = fileName.lastIndexOf("/");
                if (index > -1) {
                    fileName = fileName.substring(index);
                }

                // 检查文件是否允许上传
                index = fileName.lastIndexOf(".");
                if (index > -1 && index < fileName.length() - 1) {
                    String ext = fileName.substring(index + 1).toLowerCase();
                    if (!ConfigUtils.getString("web.files.upload.extension").contains(";" + ext + ";")) {
                        LOGGER.warn("The file {} is not allowed to upload.", fileName);
                        continue;
                    }
                }

                // 生成唯一文件名,保留原文件名
                String newFileName = UUID.randomUUID().toString();
                
                // 将文件内容写到服务器端
                String targetPath = targetFolderPath + "/" + newFileName;
                File targetFile = new File(targetPath);// 目标文件
                targetFile.createNewFile();
                fileItem.write(targetFile);

                fileItem.delete();// 删除临时文件
                fileMap.put(fileName, newFileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}
 
Example 22
Project: melon   File: UploadUtils.java   View Source Code Vote up 5 votes
/**
  * 处理上传内容
  *
  * @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 23
Project: beyondj   File: InstallationServlet.java   View Source Code Vote up 5 votes
@Override
public void init() throws ServletException {
    super.init();
    String uploadLocation = getTempUploadLocation();
    File filesDir = new File(uploadLocation);
    filesDir.mkdirs();

    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    fileFactory.setRepository(filesDir);
    this.upoader = new ServletFileUpload(fileFactory);
}
 
Example 24
Project: dataforms   File: DataFormsServlet.java   View Source Code Vote up 5 votes
/**
 * File Uploadがある場合のパラメータ解析を行います。
 * @param req HTTPリクエスト。
 * @return パラメータ解析結果。
 * @throws Exception 例外。
 */
private Map<String, Object> getParameterMapForMultipart(final HttpServletRequest req) throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(new File(tempDir)); //一時的に保存する際のディレクトリ
	ServletFileUpload upload = new ServletFileUpload(factory);
	upload.setHeaderEncoding(encoding);
	@SuppressWarnings("unchecked")
	List<FileItem> list = upload.parseRequest(req);
	for (FileItem item : list) {
		String key = item.getFieldName();
		if (key != null) {
			if (item.isFormField()) {
				String value = item.getString(encoding);
				this.addParamMap(map, key, value);
			} else {
				String filename = item.getName();
				if (StringUtil.isBlank(filename)) {
					map.put(key, null);
				} else {
					map.put(key, item);
				}
			}
		}
	}
	return map;
}
 
Example 25
Project: ProteanBear_Java   File: FileUploader.java   View Source Code Vote up 5 votes
private ServletFileUpload getFileUploadComponent()
{
    DiskFileItemFactory dif=new DiskFileItemFactory();

    if(factorySizeThreshold!=DEFAULT_SIZE_THRESHOLD)
    {
        dif.setSizeThreshold(factorySizeThreshold);
    }
    if(factoryRepository!=null)
    {
        dif.setRepository(new File(factoryRepository));
    }
    if(factoryCleaningTracker!=null)
    {
        dif.setFileCleaningTracker(factoryCleaningTracker);
    }

    ServletFileUpload sfu=new ServletFileUpload(dif);

    if(sizeMax!=NO_LIMIT_SIZE_MAX)
    {
        sfu.setSizeMax(sizeMax);
    }
    if(fileSizeMax!=NO_LIMIT_FILE_SIZE_MAX)
    {
        sfu.setFileSizeMax(fileSizeMax);
    }
    if(servletHeaderencoding!=null)
    {
        sfu.setHeaderEncoding(servletHeaderencoding);
    }
    if(servletProgressListener!=null)
    {
        sfu.setProgressListener(servletProgressListener);
    }

    return sfu;
}
 
Example 26
Project: Express4J   File: FileUploadHelper.java   View Source Code Vote up 5 votes
/**
 * Init Method
 * @param servletContext
 */
public static void init(ServletContext servletContext){
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Configure a repository (to ensure a secure temp location is used)
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    fileUpload = new ServletFileUpload(factory);
    long fileMaxSize = Express4JConfig.getMaxFileSize();
    fileUpload.setFileSizeMax(fileMaxSize);
    fileUpload.setHeaderEncoding(DEFAULT_FIELD_ENCODING);
}
 
Example 27
Project: dosya   File: UploadDownloadFileServlet.java   View Source Code Vote up 5 votes
@Override
public void init() throws ServletException{
    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
    fileFactory.setRepository(filesDir);
    this.uploader = new ServletFileUpload(fileFactory);
}
 
Example 28
Project: epubcheck-web   File: EpubCheckServlet.java   View Source Code Vote up 5 votes
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	resp.setContentType("text/plain");
	PrintWriter out = resp.getWriter();
	if (!ServletFileUpload.isMultipartContent(req)) {
		out
				.println("Invalid request type");
		return;
	}
	try {
		DiskFileItemFactory itemFac = new DiskFileItemFactory();
		// itemFac.setSizeThreshold(20000000); // bytes
		File repositoryPath = new File("upload");
		repositoryPath.mkdir();
		itemFac.setRepository(repositoryPath);
		ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac);
		List fileItemList = servletFileUpload.parseRequest(req);
		Iterator list = fileItemList.iterator();
		FileItem book = null;
		while (list.hasNext()) {
			FileItem item = (FileItem) list.next();
			String paramName = item.getFieldName();
			if (paramName.equals("file"))
				book = item;
		}
		if (book == null) {
			out.println("Invalid request: no epub uploaded");
			return;
		}
		File bookFile = File.createTempFile("work", "epub");
		book.write(bookFile);
		EpubCheck epubCheck = new EpubCheck(bookFile, out);
		if( epubCheck.validate() )
			out.println("No errors or warnings detected");
		book.delete();
	} catch (Exception e) {
		out.println("Internal Server Error");
		e.printStackTrace(out);
	}
}
 
Example 29
Project: odo   File: Proxy.java   View Source Code Vote up 5 votes
private DiskFileItemFactory createDiskFactory() {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    return diskFileItemFactory;
}
 
Example 30
Project: screenshot-service   File: HtmlScreenshotServlet.java   View Source Code Vote up 5 votes
/**
 * Read Multipart files from {@link HttpServletRequest}
 * 
 * @param req
 * @return
 * @throws IOException
 * @throws FileUploadException
 */
private List<FileItem> getUploadedFiles(HttpServletRequest req)
		throws IOException, FileUploadException {
	File repository = File.createTempFile("servlet", null).getParentFile();
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(repository);
	ServletFileUpload fileUpload = new ServletFileUpload(factory);
	return fileUpload.parseRequest(req);
}
 
Example 31
Project: caarray   File: MonitoredMultiPartRequest.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@SuppressWarnings({"unchecked", "PMD.CyclomaticComplexity" })
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    ProgressMonitor monitor = null;
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        monitor = new ProgressMonitor();
        upload.setProgressListener(monitor);
        String uploadKey = getUploadKey(servletRequest);
        servletRequest.getSession().setAttribute(uploadKey, monitor);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(createRequestContext(servletRequest));
        for (FileItem item : items) {
            LOG.debug((new StringBuilder()).append("Found item ").append(item.getFieldName()).toString());
            if (item.isFormField()) {
                handleFormField(servletRequest, item);
            } else {
                handleFileUpload(item);
            }
        }
        handleChunkedUploadHeaders(servletRequest);
    } catch (FileUploadException e) {
        if (monitor != null) {
            monitor.abort();
        }
        LOG.warn("Error processing upload", e);
        errors.add(e.getMessage());
    }
}
 
Example 32
Project: backside-servlet-ks   File: UploadHelper.java   View Source Code Vote up 4 votes
public void executePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String path = getPath(request);
	String thePath = fileBasePath+"uploads/"; //TODO calculate the directory path for this file
	/////////////////////////////
	//TODO: thePath will be dependent on a verb retrieved from request
	/////////////////////////////
	String verb = getVerb(path);
	String userId = "";
	if (verb.equals("uUpload") ||
		verb.equals("muUpload")) {
		System.out.println("UserUpload "+thePath);
		//user upload
		userId = getUserId(path);
		String tempPath = thePath+userId;
		File dir = new File(tempPath);
		if (!dir.exists()) {
			boolean foo = dir.mkdir();
			System.out.println("MADEDIR "+foo);
		}
		thePath = dir.getAbsolutePath();
	}
	try {
		System.out.println("UPLOADING TO "+verb+" | "+userId+" | "+thePath);
		File repository = new File(thePath);
    	String uploadPath = repository.getAbsolutePath()+"/";
    	DiskFileItemFactory dfiFactory = dfiFactory = new DiskFileItemFactory();
    	dfiFactory.setRepository(repository);
		ServletFileUpload servletFileUpload = new ServletFileUpload(dfiFactory);
		System.out.println("PARSING");
		List<FileItem> items = servletFileUpload.parseRequest(request);
		System.out.println("FILEUPLOADING "+path+
				" | "+items.size());
		Iterator<FileItem> iter = items.iterator();
   		while (iter.hasNext()) {
   		    FileItem item = iter.next();
	    	String fileName = item.getName();

   		    if (item.isFormField()) {
   		        //TODO processFormField(item);
   		    } else {
   		        //TODOprocessUploadedFile(item);
   		    	File f = new File(uploadPath+fileName);
   		    	item.write(f);
   		    }
   		    //TODO would be nice to have a socket and show progress
   		} 		} catch (Exception e) {
		environment.logError(e.getMessage(), e);
		e.printStackTrace();
	}
	if (verb.equals("uUpload"))
		response.sendRedirect("/gui");
	else
		sendHTML("ok", response);
}
 
Example 33
Project: urule   File: VariableEditorServletHandler.java   View Source Code Vote up 4 votes
public void importXml(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	try {
		List<FileItem> items = upload.parseRequest(req);
		if(items.size()!=1){
			throw new ServletException("Upload xml file is invalid.");
		}
		FileItem item=items.get(0);
		inputStream=item.getInputStream();
		String xmlContent=IOUtils.toString(inputStream, "utf-8");
		List<Variable> variables=new ArrayList<Variable>();
		Document doc=DocumentHelper.parseText(xmlContent);
		Element root=doc.getRootElement();
		String clazz=root.attributeValue("clazz");
		for(Object obj:root.elements()){
			if(obj==null || !(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			Variable var=new Variable();
			var.setAct(Act.InOut);
			var.setDefaultValue(ele.attributeValue("defaultValue"));
			var.setLabel(ele.attributeValue("label"));
			var.setName(ele.attributeValue("name"));
			var.setType(Datatype.valueOf(ele.attributeValue("type")));
			variables.add(var);
		}
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("clazz", clazz);
		result.put("variables", variables);
		writeObjectToJson(resp, result);
	} catch (Exception e) {
		throw new ServletException(e);
	} finally {
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example 34
Project: convertigo-engine   File: GenericServlet.java   View Source Code Vote up 4 votes
public Object processRequest(HttpServletRequest request) throws Exception {
	HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;
	File temporaryFile = null;

	try {
		// Check multipart request
		if (ServletFileUpload.isMultipartContent(request)) {
			Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			factory.setSizeThreshold(1000);

			temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
			int cptFile = 0;
			temporaryFile.delete();
			temporaryFile.mkdirs();
			factory.setRepository(temporaryFile);
			Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath());

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

			// Set overall request size constraint
			upload.setSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
			upload.setFileSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

			// Parse the request
			List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

			for (FileItem fileItem : items) {
				String parameterName = fileItem.getFieldName();
				String parameterValue;
				if (fileItem.isFormField()) {
					parameterValue = fileItem.getString();
					Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue);
				} else {
					String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
					if (name.length() > 0) {
						File wDir = new File(temporaryFile, "" + (++cptFile));
						wDir.mkdirs();
						File wFile = new File(wDir, name);
						fileItem.write(wFile);
						fileItem.delete();
						parameterValue = wFile.getAbsolutePath();
						Engine.logContext.debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue);
					} else {
						Engine.logContext.debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name");
						parameterValue = "";
					}
				}

				if (twsRequest != null) {
					twsRequest.addParameter(parameterName, parameterValue);
				}
			}
		}
		
		Requester requester = getRequester();
		request.setAttribute("convertigo.requester", requester);

		Object result = requester.processRequest(request);

		processRequestEnd(request, requester);
		
		return result;
	} finally {
		if (temporaryFile != null) {
			try {
				Engine.logEngine.debug("(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
				FileUtils.deleteDirectory(temporaryFile);
			} catch (IOException e) { }
		}
	}
}
 
Example 35
Project: Java-education   File: ImageServlet.java   View Source Code Vote up 4 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    HttpSession session = req.getSession(false);
    Integer userId = (int)session.getAttribute("id_user");
    Integer orderId = (int)session.getAttribute("currentOrder");
    PrintWriter out = resp.getWriter();
    JsonObject jsonObject = new JsonObject();

    if(isMultipart && userId != -1 && orderId != -1){
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();

        FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(servletContext);
        factory.setFileCleaningTracker(tracker);
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

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

        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem imageFile : items){
                byte[] imageByte = imageFile.get();
                Order order = new Order();
                order.setId(orderId);
                Image image = new Image();
                image.setDataimage(imageByte);
                image.setOrder(order);
                new ImageDBManager().create(image);
            }
            jsonObject.addProperty("success", true);

        } catch (FileUploadException e) {
            jsonObject.addProperty("success", false);
            e.printStackTrace();
        }
    } else {
        jsonObject.addProperty("success", false);
    }

    out.append(jsonObject.toString());
    out.flush();


}
 
Example 36
Project: giiwa   File: Model.java   View Source Code Vote up 4 votes
/**
 * get files or multiple-part request
 * 
 * @return
 */
@SuppressWarnings("unchecked")
final private Map<String, Object> getFiles() {
	if (uploads == null) {
		uploads = new HashMap<String, Object>();
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		File repository = (File) s️ervletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

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

		// Parse the request
		try {
			List<FileItem> items = upload.parseRequest(req);
			if (items != null && items.size() > 0) {
				for (FileItem f : items) {
					if (uploads.containsKey(f.getFieldName())) {
						Object o = uploads.get(f.getFieldName());
						if (o instanceof FileItem) {
							List<FileItem> list = new ArrayList<FileItem>();
							list.add((FileItem) o);
							list.add(f);
							uploads.put(f.getFieldName(), list);
						} else if (o instanceof List) {
							((List<FileItem>) o).add(f);
						}
					} else {
						uploads.put(f.getFieldName(), f);
					}
				}
			} else {
				if (log.isWarnEnabled())
					log.warn("nothing got!!!");
			}
		} catch (FileUploadException e) {
			if (log.isErrorEnabled())
				log.error(e.getMessage(), e);
		}
	}

	return uploads;
}
 
Example 37
Project: bisis-v4   File: FileManagerServlet.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
private void handleUpload(HttpServletRequest req, HttpServletResponse res) 
    throws FileUploadException {  	
	
	 DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(sizeThreshold);
  factory.setRepository(tempDir);
  
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(maxSize);
  
  Iterator items = upload.parseRequest(req).iterator();
  DocFile docFile = new DocFile();
  FileItem fileItem = null;
  
  while (items.hasNext()) {    	
    FileItem item = (FileItem)items.next();     
    if (item.isFormField())
      processTextField(item, docFile);
    else
      fileItem = item;
  }
  if (docFile.getRn() == 0)
    throw new FileUploadException("RN not defined for: " + docFile);
  if (docFile.getFilename() == null)
    throw new FileUploadException("Filename not defined for: " + docFile);
  if (docFile.getUploader() == null)
    throw new FileUploadException("Uploader not defined for: " + docFile);
  if (docFile.getContentType() == null)
    docFile.setContentType(
        MimeTypes.guessMimeTypeFromFilename(docFile.getFilename()));
  if (docFile.getContentType() == null)
    throw new FileUploadException("Content type unknown for: " + docFile);    
  try {
  		
    Connection conn = dataSource.getConnection();
    List<DocFile> docFiles = DocFile.find(conn, docFile.getRn());
    boolean overwrite = false;
    if (docFiles.size() > 0) {
    	for (DocFile df:docFiles) {
    		if (df.getFilename().equalsIgnoreCase(docFile.getFilename())) {
    			// overwrite
    			df.setUploader(docFile.getUploader());
    			df.update(conn);
    			overwrite = true;
    			break;
    		}
    	}
    }
    if (!overwrite) { 
  	//dodati u indeks da zapis sa RN imam elektronski resurs odredjenog tipa:.doc, .pdf...
  	boolean ok=addToIndex(docFile.getRn(),docFile.getContentType());  
  	if (!ok){
  		log.fatal("Informacija da zapis "+docFile.getRn()+" ima elektronske resurse nije indeksirana");
  	    throw new FileUploadException("Upload error:Informacija da zapis "+docFile.getRn()+" ima elektronske resurse nije indeksirana");
  	}
    	docFile.store(conn); // sada ce i atribut id biti upisan u objekat
    }
    FileStorage.store(docFile, fileItem);
    conn.commit();
    conn.close();
  } catch (Exception ex) {    	 
    log.fatal(ex);
    throw new FileUploadException("Upload error", ex);
  }
}
 
Example 38
Project: Shop-for-JavaWeb   File: UploadUtils.java   View Source Code Vote up 4 votes
/**
	 * 处理上传内容
	 * 
	 * @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 39
Project: nbone   File: HttpFileUpload.java   View Source Code Vote up 4 votes
/**
 * 将上传的文件放到指定的目录下
 * @param request HttpServletRequest对象
 * @param sourceFolder 指定文件夹
 * @param fileName 指定文件名,包含扩展名(数组)
 * @return List 返回文件名集合
 * @throws Exception 抛出异常
 */
public List uploadFile2Folder(HttpServletRequest request,String sourceFolder,String[] fileName)throws Exception{
	DiskFileItemFactory factory = new DiskFileItemFactory();
	if(sizeThreshold!=0){
		factory.setSizeThreshold(sizeThreshold);
	}
	if(repositoryPath!=null){
		factory.setRepository(new File(repositoryPath));
	}
	ServletFileUpload upload = new ServletFileUpload(factory);
	if(sourceFolder==null){
	    sourceFolder="";
	}
	if(sizeMax!=0){
		upload.setSizeMax(sizeMax);
	}
	if(encoding!=null){
		upload.setHeaderEncoding(encoding);
	}
	
	//若指定文件加不存在,则创建
	List list = new ArrayList();
	File file=new File(sourceFolder);
	if(!file.exists()){
		file.mkdir();
	}
	//开始读取上传信息 
	List fileItems = upload.parseRequest(request); 
	if(fileItems!=null&&fileItems.size()!=0){
		Iterator it=fileItems.iterator();
		int i=0;
		while(it.hasNext()){
			FileItem fi=(FileItem)it.next();
			if(!fi.isFormField()){  
			        //忽略其他不是文档域的任何表单信息
				String name=fi.getName();
				String nameDir=name;
				if(name.lastIndexOf("\\")>=0){
					nameDir=name.substring(name.lastIndexOf("\\"));
				}
				String type=null;
				if(nameDir.lastIndexOf(".")>=0){
					type=nameDir.substring(nameDir.lastIndexOf(".")+1);
				}
				//自己指定文件名 
				if(fileName!=null){
					if(fileName[i]!=null){
					    nameDir=fileName[i];
					}
					i++;
				}
				//判断是否设定了上传的文件类型
				if(type!=null&&!isHave(types,type)){
					File f=new File(sourceFolder+nameDir);
					fi.write(f);
					list.add(sourceFolder+nameDir);
				}
			}
		}
	}
	return list;
}
 
Example 40
Project: NPush   File: FileUploadServlet.java   View Source Code Vote up 4 votes
/**
 * 将上传的数据流存入临时文件
 * 
 * @param fileSourcel
 *            上传流
 * @param tempFile
 *            临时文件
 * @throws IOException
 */
private String writeToFile(HttpServletRequest request) throws IOException {
	//获取网络访问路径
	String path = request.getContextPath();
	StringBuffer fileUrl = new StringBuffer();
	fileUrl.append(request.getScheme()).append("://").append(request.getServerName()).
		append(":").append(request.getServerPort()).append(path).append("/files/audio/");
	
	File audioDir = new File(this.audioFileFolder);
	if (!audioDir.exists()) {
		audioDir.mkdirs();
	}

	File tempDir = new File(this.tempFileFolder);
	if (!tempDir.exists()) {
		tempDir.mkdirs();
	}

	try {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Set factory constraints
		factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
		factory.setRepository(tempDir);// 设置缓冲区目录

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

		// Set overall request size constraint
		upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB

		List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
		Iterator<FileItem> i = items.iterator();
		while (i.hasNext()) {
			FileItem fi = (FileItem) i.next();
			String fileName = fi.getName();
			if (fileName != null) {
				File fullFile = new File(fi.getName());
				File savedFile = new File(this.audioFileFolder, fullFile.getName());
				fi.write(savedFile);
				fileUrl.append(fileName);
			}
		}
		logger.info("===文件已上传===");
	} catch (Exception e) {
		// 可以跳转出错页面
		logger.error("错误原因:" + e.getMessage());
	}
	return fileUrl.toString();
}
 
Example 41
Project: Sketchy   File: ImageUploadServlet.java   View Source Code Vote up 4 votes
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
	try{
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart){
			    			
 		DiskFileItemFactory factory = new DiskFileItemFactory();
 		factory.setRepository(FileUtils.getTempDirectory());
 		factory.setSizeThreshold(MAX_SIZE);

 		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
  	List<FileItem> files = servletFileUpload.parseRequest(request);
  	for (FileItem fileItem:files){
  		String uploadFileName = fileItem.getName();
  		if (StringUtils.isNotBlank(uploadFileName)){
  			// Don't allow \\ in the filename, assume it's a directory separator and convert to "/"
  			// and take the filename after the last "/"
  			// This will fix the issue of Jetty not reading and serving files
  			// with "\" (%5C) characters 
  			// This also fixes the issue of IE sometimes sending the whole path 
  			// (depending on the security settings)
  			uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/");
  			if (StringUtils.contains(uploadFileName, "/")){
  				uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/");
  			}
  			
   		File uploadFile = HttpServer.getUploadFile(uploadFileName);
   		// make sure filename is actually in the upload directory
   		// we don't want any funny games
   		if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)){
   			throw new RuntimeException("Can not upload File. Invalid directory!");
   		}

   		// if saved ok, then need to add the data file
   		SourceImageAttributes sourceImageAttributes = new SourceImageAttributes();
   		sourceImageAttributes.setImageName(uploadFileName);

   		File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename());
   		if (pngFile.exists()) {
   			throw new Exception("Can not Upload file. File '" + uploadFileName +"' already exists!");
   		}
   		File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename());

   		// Convert the image to a .PNG file
   		BufferedImage image=ImageUtils.loadImage(fileItem.getInputStream());
   		ImageUtils.saveImage(pngFile, image);
   		
   		sourceImageAttributes.setWidth(image.getWidth());
   		sourceImageAttributes.setHeight(image.getHeight());

   		FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson());
   		jsonServletResult.put("imageName", uploadFileName);
  		}
  	}
		}
	} catch (Exception e){
		jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage());
	}
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(jsonServletResult.toJSONString());
}
 
Example 42
Project: ECRM   File: ScheduleController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "import")
public String importFile(HttpServletRequest request) throws IOException, InvalidFormatException, ParseException {
    HttpSession session = request.getSession();
    if (session != null) {
        String fileName = "";
        File file;
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        String filePath = "/path/to/uploads";
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File("/path/to/uploads"));
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();

                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        fileName = fi.getName();
                        ServletContext servletContext = request.getSession().getServletContext();
                        filePath = servletContext.getRealPath(fileName);
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath);
                        } else {
                            file = new File(filePath);
                        }
                        fi.write(file);
                    }
                }

            } catch (Exception ex) {
                System.out.println(ex);
            }
            return scheduleService.importSchedule(filePath);
        }

        return "redirect:/staff/schedule";
    } else {
        return "Login";
    }
}
 
Example 43
Project: ECRM   File: EquipmentController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "/createCategory", method = RequestMethod.POST)
public String createCategory(HttpServletRequest request, HttpSession httpSession) {
    HttpSession session = request.getSession();
    if (session != null) {
        try {
            String fileName = "";
            File file;
            int maxFileSize = 5000 * 1024;
            int maxMemSize = 5000 * 1024;
            String filePath = "";
            String contentType = request.getContentType();
            Hashtable<String, String> params = new Hashtable<String, String>();

            if ((contentType.indexOf("multipart/form-data") >= 0)) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // maximum size that will be stored in memory
                factory.setSizeThreshold(maxMemSize);
                // Location to save data that is larger than maxMemSize.
                factory.setRepository(new File("/path/to/uploads"));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // maximum file size to be uploaded.
                upload.setSizeMax(maxFileSize);
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);
                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        fileName = fi.getName();
                        fileName = fileName.replace("-", "");
                        ServletContext servletContext = request.getSession().getServletContext();
                        filePath = servletContext.getRealPath("/resource/img/equipment/");
                        String saveFile = filePath + "/" + fileName;
                        // Write the file
                        file = new File(saveFile);
                        fi.write(file);
                    } else {
                        String fieldName = fi.getFieldName();
                        String fieldValue = fi.getString();
                        params.put(fieldName, fieldValue);
                    }
                }


            }
            String name = params.get("name");
            String isManaged = params.get("isManaged");
            double expiredTime = Double.parseDouble(params.get("expiredTime"));
            boolean managed = false;
            if (isManaged.equals("1")) {
                managed = true;
            }
            TblEquipmentCategoryEntity tblEquipmentCategoryEntity = new TblEquipmentCategoryEntity(name, managed, fileName, false,
                    new Date().getTime(), expiredTime);
            categoryDAO.persist(tblEquipmentCategoryEntity);
            return "redirect:/staff/equipment?ACTIVETAB=tab2";
        } catch (Exception ex) {
            System.out.println(ex);
            return "Error";
        }
    } else {
        return "Login";
    }

}
 
Example 44
Project: ECRM   File: EquipmentController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "/editCategory", method = RequestMethod.POST)
public String editCategory(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (session != null) {
        try {
            String fileName = "";
            File file;
            int maxFileSize = 5000 * 1024;
            int maxMemSize = 5000 * 1024;
            String filePath = "";
            String contentType = request.getContentType();
            Hashtable<String, String> params = new Hashtable<String, String>();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // maximum size that will be stored in memory
                factory.setSizeThreshold(maxMemSize);
                // Location to save data that is larger than maxMemSize.
                factory.setRepository(new File("/path/to/uploads"));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // maximum file size to be uploaded.
                upload.setSizeMax(maxFileSize);
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);
                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        fileName = fi.getName();
                        fileName = fileName.replace("-", "");
                        ServletContext servletContext = request.getSession().getServletContext();
                        filePath = servletContext.getRealPath("/resource/img/equipment/");
                        String saveFile = filePath + "/" + fileName;
                        // Write the file
                        file = new File(saveFile);
                        fi.write(file);
                    } else {
                        String fieldName = fi.getFieldName();
                        String fieldValue = fi.getString();
                        params.put(fieldName, fieldValue);
                    }
                }
            }
            String categoryId = params.get("categoryId");
            String categoryName = params.get("name");
            double expiredTime = Double.parseDouble(params.get("expiredTime"));
            TblEquipmentCategoryEntity tblEquipmentCategoryEntity = categoryDAO.find(Integer.parseInt(categoryId));
            tblEquipmentCategoryEntity.setImageUrl(fileName);
            tblEquipmentCategoryEntity.setName(categoryName.trim());
            tblEquipmentCategoryEntity.setUpdateTime(new Date().getTime());
            tblEquipmentCategoryEntity.setExpiredTime(expiredTime);
            categoryDAO.merge(tblEquipmentCategoryEntity);
            return "redirect:/staff/equipment?ACTIVETAB=tab2";
        } catch (Exception ex) {
            System.out.println(ex);
            return "Error";
        }
    } else {
        return "Login";
    }
}
 
Example 45
Project: scheduling-portal   File: LoginServlet.java   View Source Code Vote up 4 votes
private void login(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");
    File cred = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String user = "";
        String pass = "";
        String sshKey = "";

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();

                if (name.equals("username")) {
                    user = value;
                } else if (name.equals("password")) {
                    pass = value;
                }
            } else {
                String field = fi.getFieldName();

                byte[] bytes = IOUtils.toByteArray(fi.getInputStream());

                if (field.equals("credential")) {
                    cred = File.createTempFile("credential", null);
                    cred.deleteOnExit();
                    fi.write(cred);
                } else if (field.equals("sshkey")) {
                    sshKey = new String(bytes);
                }
            }

            fi.delete();
        }

        String sessionId = Service.get().login(user, pass, cred, sshKey);
        String userName = Service.get().getLoginFromSessionId(sessionId);
        String s = "{ \"sessionId\" : \"" + sessionId + "\" , \"username\" : \"" + userName + "\" }";
        response.getWriter().write(SafeHtmlUtils.htmlEscape(s));
    } catch (Throwable t) {
        try {
            response.getWriter().write(SafeHtmlUtils.htmlEscape(t.getMessage()));
        } catch (IOException e1) {
            LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1);
        }
    } finally {
        if (cred != null)
            cred.delete();
    }
}
 
Example 46
Project: scheduling-portal   File: CredentialsServlet.java   View Source Code Vote up 4 votes
private void login(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String user = "";
        String pass = "";
        String sshKey = "";

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();

                if (name.equals("username")) {
                    user = value;
                } else if (name.equals("password")) {
                    pass = value;
                }
            } else {
                String field = fi.getFieldName();
                byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                if (field.equals("sshkey")) {
                    sshKey = new String(bytes);
                }
            }
            fi.delete();
        }

        String responseS = Service.get().createCredentials(user, pass, sshKey);
        response.setHeader("Content-disposition", "attachment; filename=" + user + "_cred.txt");
        response.setHeader("Location", "" + user + ".cred.txt");
        response.getWriter().write(responseS);

    } catch (Throwable t) {
        try {
            response.getWriter().write(t.getMessage());
        } catch (IOException e1) {
            LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1);
        }
    }
}
 
Example 47
Project: jpublish   File: ProxyServlet.java   View Source Code Vote up 4 votes
/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 */
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(
                        fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(
                        fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(
                                fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[]{}),
                postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}
 
Example 48
Project: MIRROR   File: FileUploadServlet.java   View Source Code Vote up 4 votes
@Override
public void init() throws ServletException{
      DiskFileItemFactory fileFactory = new DiskFileItemFactory();
      File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
      fileFactory.setRepository(filesDir);
}
 
Example 49
Project: OLE-INST   File: DocumentResources.java   View Source Code Vote up 4 votes
/**
 * This methods reads the uploaded file content from request and returns the file content
 *
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
private String getFileContent(@Context HttpServletRequest request, @Context HttpServletResponse response)
        throws IOException

{
    int maxFileSize = 100 * 1024;
    int maxMemSize = 4 * 1024;
    File file = null;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    File output = File.createTempFile("ingest.", ".output");
    FileUtils.deleteQuietly(output);
    factory.setRepository(output);

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

    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    String fileData = null;
    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {

                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                LOG.debug("item Name = " + fi.getName() + " ; content type = " + fi.getContentType());
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                // Write the file
                fi.write(output);
                LOG.debug("Uploaded Filename: " + fileName);
                LOG.debug("Uploaded output path: " + output.getAbsolutePath());
            }
        }
        fileData = FileUtils.readFileToString(output, "UTF-8");
        output.delete();

    } catch (Exception ex) {
        LOG.error("error while ingesting :" + ex);
    }

    return fileData;
}
 
Example 50
Project: GeoprocessingAppstore   File: MultipartWrapper.java   View Source Code Vote up 4 votes
/**
 * Construct with a current HTTP servlet request.
 * @param request the current HTTP servlet request
 * @throws FileUploadException if an exception occurs during file upload
 */
public MultipartWrapper(HttpServletRequest request) 
  throws FileUploadException {
  super(request);
  getLogger().finer("Handling multipart content.");
  
  // initialize parameters
  _fileParameters = new HashMap<String,FileItem>(); 
  _formParameters = new HashMap<String,String[]>();
  int nFileSizeMax   = 100000000;
  int nSizeThreshold = 500000;
  String sTmpFolder  = "";
       
  // make the file item factory
  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(nSizeThreshold);
  if (sTmpFolder.length() > 0) {
    File fTmpFolder = new File(sTmpFolder);
    factory.setRepository(fTmpFolder);
  }
  
  // make the file upload object
  ServletFileUpload fileUpload = new ServletFileUpload();
  fileUpload.setFileItemFactory(factory);
  fileUpload.setFileSizeMax(nFileSizeMax);
  
  // parse the parameters associated with the request
  List items = fileUpload.parseRequest(request);
  String[] aValues;
  ArrayList<String> lValues;
  for(int i=0;i<items.size();i++){
    FileItem item = (FileItem)items.get(i);
    getLogger().finer("FileItem="+item);
    if (item.isFormField()) {
      String sName = item.getFieldName();
      String sValue = item.getString();
      if (_formParameters.containsKey(sName)) {
        aValues = _formParameters.get(sName);
        lValues = new ArrayList<String>(Arrays.asList(aValues));
        lValues.add(sValue);
        aValues = lValues.toArray(new String[0]);
      } else {
        aValues = new String[1];
        aValues[0] = sValue;
      }
      _formParameters.put(sName,aValues); 
    } else {
      _fileParameters.put(item.getFieldName(),item);   
      request.setAttribute(item.getFieldName(),item);
    } 
  }
}
 
Example 51
Project: android-lite-http   File: PostReceiver.java   View Source Code Vote up 4 votes
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {

    //String fileDir = "D:\\Downloads";
    //这是我的Mac笔记本上的位置,开发者设置为合适自己的文件夹,尤其windows系统。
    String fileDir = "/Users/matianyu/downloads/lite-http-v3/";

    String contentType = request.getContentType();
    System.out.println("_________________ content type: " + contentType);

    // 接受一般参数

    Map<String, String[]> map = request.getParameterMap();
    if (map.size() > 0) {
        System.out.println("_________________ http params - start");
        for (Entry<String, String[]> en : map.entrySet()) {
            System.out.println(en.getKey() + " : " + Arrays.toString(en.getValue()));
        }
        System.out.println("_________________ http params - over");
    }

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    // 接受文件和流

    PrintWriter writer = response.getWriter();
    writer.println("contentType:" + contentType);

    if (contentType != null) {
        if (contentType.startsWith("multipart")) {
            //向客户端发送响应正文
            try {
                //创建一个基于硬盘的FileItem工厂
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //设置向硬盘写数据时所用的缓冲区的大小,此处为4K
                factory.setSizeThreshold(4 * 1024);
                //设置临时目录
                factory.setRepository(new File(fileDir));
                //创建一个文件上传处理器
                ServletFileUpload upload = new ServletFileUpload(factory);

                //设置允许上传的文件的最大尺寸,此处为100M
                upload.setSizeMax(100 * 1024 * 1024);
                Map<String, List<FileItem>> itemMap = upload.parseParameterMap(request);
                for (List<FileItem> items : itemMap.values()) {
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            processFormField(item, writer); //处理普通的表单域
                        } else {
                            processUploadedFile(fileDir, item, writer); //处理上传文件
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (contentType.contains("text")
                   || contentType.contains("json")
                   || contentType.contains("application/x-www-form-urlencoded")
                   || contentType.contains("xml")) {
            processString(request);
        } else {
            processEntity(fileDir, request);
        }
    } else {
        processString(request);
    }
    System.out.println("doPost over");
    writer.print("upload over. ");
}
 
Example 52
Project: testgrid   File: HttpFileTransferTargetAcceptor.java   View Source Code Vote up 4 votes
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (!isMultipart) {
		if (request.getParameter("workspace") != null) {
			workspace = new File(request.getParameter("workspace"));
		} else {
			response.sendError(HttpStatus.SC_METHOD_FAILURE, "Invalid request Type[ not multipart]");
		}
		return;
	}
	DiskFileItemFactory factory = new DiskFileItemFactory();
	// maximum size that will be stored in memory
	factory.setSizeThreshold(maxMemSize);
	// Location to save data that is larger than maxMemSize.
	if (workspace == null)
		workspace = new File("workspace");
	factory.setRepository(workspace);

	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);
	// maximum file size to be uploaded.
	upload.setSizeMax(maxFileSize);

	try {
		// Parse the request to get file items.
		List<FileItem> fileItems = upload.parseRequest(request);
		// Process the uploaded file items
		Iterator<FileItem> i = fileItems.iterator();
		File file = null;
		FileItem fi = null;
		String filePath = null;
		File tokenFolder = null;
		while (i.hasNext()) {
			fi = i.next();
			if (fi.isFormField()) {
				String fieldName = fi.getFieldName();
				if (fieldName.equalsIgnoreCase("token")) {
					filePath = fi.getString();
					tokenFolder = new File(workspace, filePath);
					if (tokenFolder.exists()) {
						if (tokenFolder.isDirectory())
							FileUtils.deleteDirectory(tokenFolder);
						else
							tokenFolder.delete();
					}
					tokenFolder.mkdirs();
					log.info("current task folder is :{}", tokenFolder.getAbsolutePath());
					break;
				}
			}
		}

		i = fileItems.iterator();
		while (i.hasNext()) {
			fi = i.next();
			if (!fi.isFormField()) {
				// Get the uploaded file parameters
				String fileName = fi.getName().replaceAll("\\\\", "/");
				// Write the file
				if (fileName.lastIndexOf("/") >= 0) {
					file = new File(tokenFolder, fileName.substring(fileName.lastIndexOf("/")));
				} else {
					file = new File(tokenFolder, fileName.substring(fileName.lastIndexOf("/") + 1));
				}
				fi.write(file);
				log.info("Uploaded Filename: {}", fileName);
			}
		}
	} catch (Exception ex) {
		log.error("Got exception when receiving uploding files.", ex);
		response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Got exception when receiving uploding files:" + ex.getMessage());
	}
}
 
Example 53
Project: dis-timeintervaldataanalyzer   File: LoaderServlet.java   View Source Code Vote up 4 votes
@Override
public void initialize(final Extension e) {
	factory = new DiskFileItemFactory();
	factory.setRepository(sessionManager.getTempDir());
}
 
Example 54
Project: catissue-migration-tool   File: BulkHandler.java   View Source Code Vote up 4 votes
/**
 * This method will be called to get request parameters.
 * @param request HttpServletRequest.
 * @param bulkOperationForm form.
 * @throws BulkOperationException Exception.
 */
private void getRequestParameters(HttpServletRequest request
		,BulkOperationForm bulkOperationForm) throws BulkOperationException
{
	try
	{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(CommonServiceLocator.getInstance().getAppHome()));
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

	    // If file size exceeds, a FileUploadException will be thrown
	    servletFileUpload.setSizeMax(10000*1000*100*10);
	    List<FileItem> fileItems;
			fileItems = servletFileUpload.parseRequest(request);
	    Iterator<FileItem> itr = fileItems.iterator();
	    while(itr.hasNext())
	    {
		      FileItem fileItem = itr.next();
		      //Check if not form field so as to only handle the file inputs
		      //else condition handles the submit button input
		      if(!fileItem.isFormField())
		      {
		    	 if("csvFile".equals(fileItem.getFieldName()))
		    	 {
		    		 bulkOperationForm.setCsvFile(getFormFile(fileItem));
		    	 }
		    	 else
		    	 {
		    		 bulkOperationForm.setXmlTemplateFile(getFormFile(fileItem));
		    	 }
		    	 logger.info("Field ="+fileItem.getFieldName());
		      }
		      else
		      {
		    	  if("operation".equals(fileItem.getFieldName()))
		    	  {
		    		  bulkOperationForm.setOperationName(fileItem.getString());
		    	  }

		      }
		 }
	}
	catch (Exception exp)
	{
		ErrorKey errorkey = ErrorKey.getErrorKey("bulk.operation.request.param.error");
		throw new BulkOperationException(errorkey,exp,exp.getMessage());
	}
}
 
Example 55
Project: mymam   File: UploadMultipartRequestFilter.java   View Source Code Vote up 4 votes
@Override
public void init(FilterConfig config) throws ServletException {
    factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);
    factory.setRepository(new File("/tmp"));
}
 
Example 56
Project: usgin-geoportal   File: MultipartWrapper.java   View Source Code Vote up 4 votes
/**
 * Construct with a current HTTP servlet request.
 * @param request the current HTTP servlet request
 * @throws FileUploadException if an exception occurs during file upload
 */
public MultipartWrapper(HttpServletRequest request) 
  throws FileUploadException {
  super(request);
  getLogger().finer("Handling multipart content.");
  
  // initialize parameters
  _fileParameters = new HashMap<String,FileItem>(); 
  _formParameters = new HashMap<String,String[]>();
  int nFileSizeMax   = 100000000;
  int nSizeThreshold = 500000;
  String sTmpFolder  = "";
       
  // make the file item factory
  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(nSizeThreshold);
  if (sTmpFolder.length() > 0) {
    File fTmpFolder = new File(sTmpFolder);
    factory.setRepository(fTmpFolder);
  }
  
  // make the file upload object
  ServletFileUpload fileUpload = new ServletFileUpload();
  fileUpload.setFileItemFactory(factory);
  fileUpload.setFileSizeMax(nFileSizeMax);
  
  // parse the parameters associated with the request
  List items = fileUpload.parseRequest(request);
  String[] aValues;
  ArrayList<String> lValues;
  for(int i=0;i<items.size();i++){
    FileItem item = (FileItem)items.get(i);
    getLogger().finer("FileItem="+item);
    if (item.isFormField()) {
      String sName = item.getFieldName();
      String sValue = item.getString();
      if (_formParameters.containsKey(sName)) {
        aValues = _formParameters.get(sName);
        lValues = new ArrayList<String>(Arrays.asList(aValues));
        lValues.add(sValue);
        aValues = lValues.toArray(new String[0]);
      } else {
        aValues = new String[1];
        aValues[0] = sValue;
      }
      _formParameters.put(sName,aValues); 
    } else {
      _fileParameters.put(item.getFieldName(),item);   
      request.setAttribute(item.getFieldName(),item);
    } 
  }
}
 
Example 57
Project: TupiFS-Agent   File: Connector.java   View Source Code Vote up 2 votes
/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param proxyRequest The {@link PostMethod} that we are
 * configuring to send a multipart POST request
 * @param request The {@link HttpServletRequest} that contains
 * the mutlipart POST data to be sent via the {@link PostMethod}
 * @return 
 */

private HttpPost handleMultipartPost(HttpPost proxyRequest, HttpServletRequest request) throws ServletException {


	//HttpResponse httpResponse = httpClient.execute(proxyRequest);
	
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(maxFileUploadSize);
    diskFileItemFactory.setRepository(UPLOAD_TEMP_DIRECTORY);

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

    MultipartEntityBuilder multipartRequestEntity = MultipartEntityBuilder.create();
    
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = servletFileUpload.parseRequest(request);

        

        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
            	
            	multipartRequestEntity.addTextBody(fileItemCurrent.getFieldName(), fileItemCurrent.getString());
            	
               
            } else {
                // The item is a file upload, so we create a FilePart
            	multipartRequestEntity.addBinaryBody(fileItemCurrent.getFieldName(), fileItemCurrent.get());

            }
        }

        HttpEntity entity = multipartRequestEntity.build();
        
        proxyRequest.setEntity(entity);
        

        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        //httpResponse.setHeader(CONTENT_TYPE_HEADER_NAME, entity.getContentType().getValue());
        proxyRequest.setHeader(CONTENT_TYPE_HEADER_NAME, entity.getContentType().getValue());
        
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
    
    return proxyRequest;
}