Java Code Examples for org.apache.commons.fileupload.FileItem#write()

The following examples show how to use org.apache.commons.fileupload.FileItem#write() . 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: PostReceiver.java    From android-lite-http with Apache License 2.0 6 votes vote down vote up
/**
 * 处理表单文件
 */
private void processUploadedFile(String filePath, FileItem item, PrintWriter writer) throws Exception {
    String filename = item.getName();
    int index = filename.lastIndexOf("\\");
    filename = filename.substring(index + 1, filename.length());
    long fileSize = item.getSize();
    if (filename.equals("") && fileSize == 0)
        return;
    File uploadFile = new File(filePath + "/" + filename);
    item.write(uploadFile);
    writer.println(
            "File Part [" + filename + "] is saved." + " contentType: " + item
                    .getContentType() + " , size: " + fileSize + "\r\n");
    System.out.println(
            "File Part [" + filename + "] is saved." + " contentType: " + item
                    .getContentType() + " , size: " + fileSize);
}
 
Example 2
Source File: RecorderService.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void recordUploadedFile(long executionId, TestCaseStepActionExecution tcsae, FileItem uploadedFile) {
    String UploadedfileName = new File(uploadedFile.getName()).getName();

    try {
        // UPLOADED File.
        Recorder recorder = this.initFilenames(executionId, tcsae.getTest(), tcsae.getTestCase(), String.valueOf(tcsae.getStep()), String.valueOf(tcsae.getIndex()), String.valueOf(tcsae.getSequence()), null, null, 0, "image", "jpg", false);
        File storeFile = new File(recorder.getFullFilename());
        // saves the file on disk
        uploadedFile.write(storeFile);
        LOG.info("File saved : " + recorder.getFullFilename());

        // Index file created to database.
        testCaseExecutionFileService.save(executionId, recorder.getLevel(), "Image", recorder.getRelativeFilenameURL(), "JPG", "");

    } catch (Exception ex) {
        LOG.error("File: " + UploadedfileName + " failed to be uploaded/saved: " + ex.toString(), ex);
    }

}
 
Example 3
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext().getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 4
Source File: FileUpload.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public FileUpload(FileItem fileItem) {
    this.fileItem = fileItem;
    File tmp = TempFilePlugin.createTempFolder();
    defaultFile = new File(tmp, FilenameUtils.getName(fileItem.getFieldName()) + File.separator + FilenameUtils.getName(fileItem.getName()));
    try {
        if(!defaultFile.getCanonicalPath().startsWith(tmp.getCanonicalPath())) {
            throw new IOException("Temp file try to override existing file?");
        }
        defaultFile.getParentFile().mkdirs();
        fileItem.write(defaultFile);
    } catch (Exception e) {
        throw new IllegalStateException("Error when trying to write to file " + defaultFile.getAbsolutePath(), e);
    }
}
 
Example 5
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext()
				.getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(
									item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 6
Source File: TestDataLibDAO.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Answer uploadFile(int id, FileItem file) {
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
            "cerberus_testdatalibcsv_path Parameter not found");
    AnswerItem a = parameterService.readByKey("", "cerberus_testdatalibcsv_path");
    if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
        Parameter p = (Parameter) a.getItem();
        String uploadPath = p.getValue();
        File appDir = new File(uploadPath + File.separator + id);
        if (!appDir.exists()) {
            try {
                appDir.mkdirs();
            } catch (SecurityException se) {
                LOG.warn("Unable to create testdatalib csv dir: " + se.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        se.toString());
                a.setResultMessage(msg);
            }
        }
        if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            deleteFolder(appDir, false);
            File picture = new File(uploadPath + File.separator + id + File.separator + file.getName());
            try {
                file.write(picture);
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK).resolveDescription("DESCRIPTION",
                        "TestDataLib CSV file uploaded");
                msg.setDescription(msg.getDescription().replace("%ITEM%", "testDatalib CSV").replace("%OPERATION%", "Upload"));
            } catch (Exception e) {
                LOG.warn("Unable to upload testdatalib csv file: " + e.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        e.toString());
            }
        }
    } else {
        LOG.warn("cerberus_testdatalibCSV_path Parameter not found");
    }
    a.setResultMessage(msg);
    return a;
}
 
Example 7
Source File: AppServiceDAO.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Answer uploadFile(String service, FileItem file) {
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
            "cerberus_ftpfile_path Parameter not found");
    AnswerItem a = parameterService.readByKey("", "cerberus_ftpfile_path");
    if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
        Parameter p = (Parameter) a.getItem();
        String uploadPath = p.getValue();
        File appDir = new File(uploadPath + File.separator + service);
        if (!appDir.exists()) {
            try {
                appDir.mkdirs();
            } catch (SecurityException se) {
                LOG.warn("Unable to create ftp local file dir: " + se.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        se.toString());
                a.setResultMessage(msg);
            }
        }
        if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            deleteFolder(appDir, false);
            File picture = new File(uploadPath + File.separator + service + File.separator + file.getName());
            try {
                file.write(picture);
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK).resolveDescription("DESCRIPTION",
                        "ftp local file uploaded");
                msg.setDescription(msg.getDescription().replace("%ITEM%", "FTP Local File").replace("%OPERATION%", "Upload"));
            } catch (Exception e) {
                LOG.warn("Unable to upload ftp local file: " + e.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        e.toString());
            }
        }
    } else {
        LOG.warn("cerberus_ftpfile_path Parameter not found");
    }
    a.setResultMessage(msg);
    return a;
}
 
Example 8
Source File: WebServer.java    From mirror with Apache License 2.0 5 votes vote down vote up
private String saveFileItemToDisk(FileItem fileItem) {
    Timber.d("Received file %s", fileItem.getName());
    try {
        File file = getFile(fileItem);
        Timber.d("writing file %s", file.getAbsolutePath());
        fileItem.write(getFile(fileItem));
        return file.getAbsolutePath();
    } catch (Exception e) {
        Timber.e(e, e.getMessage());
        return "";
    }
}
 
Example 9
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException {
	String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    
    if(fieldName.equalsIgnoreCase("deploymentDescriptor")) return null;
    
    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(), jobDeploymentDescriptor.getLanguage().toLowerCase());
	File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
	File tmpDir = new File(projectDir, "tmp");
	if(!tmpDir.exists()) tmpDir.mkdirs();	   
     File uploadedFile = new File(tmpDir, fileName);
    
    try {
		item.write(uploadedFile);
	} catch (Exception e) {
		e.printStackTrace();
	}	
	
	String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
	List dirNameList = new ArrayList();
	for(int i = 0; i < dirNames.length; i++) {
		if(!dirNames[i].equalsIgnoreCase("lib")) dirNameList.add(dirNames[i]);
	}
	String[] jobNames = (String[])dirNameList.toArray(new String[0]);
	
    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();	
    tmpDir.delete();
    
    return jobNames;
}
 
Example 10
Source File: UploadServlet.java    From tutorials with MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
        }
    }
 
Example 11
Source File: ApplicationObjectDAO.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Answer uploadFile(int id, FileItem file) {
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
            "cerberus_applicationobject_path Parameter not found");
    AnswerItem a = parameterService.readByKey("", "cerberus_applicationobject_path");
    if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
        Parameter p = (Parameter) a.getItem();
        String uploadPath = p.getValue();
        File appDir = new File(uploadPath + File.separator + id);
        if (!appDir.exists()) {
            try {
                appDir.mkdirs();
            } catch (SecurityException se) {
                LOG.warn("Unable to create application dir: " + se.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        se.toString());
                a.setResultMessage(msg);
            }
        }
        if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            deleteFolder(appDir, false);
            File picture = new File(uploadPath + File.separator + id + File.separator + file.getName());
            try {
                file.write(picture);
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK).resolveDescription("DESCRIPTION",
                        "Application Object file uploaded");
                msg.setDescription(msg.getDescription().replace("%ITEM%", "Application Object").replace("%OPERATION%", "Upload"));
            } catch (Exception e) {
                LOG.warn("Unable to upload application object file: " + e.getMessage());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION",
                        e.toString());
            }
        }
    } else {
        LOG.warn("cerberus_applicationobject_path Parameter not found");
    }
    a.setResultMessage(msg);
    return a;
}
 
Example 12
Source File: ServletUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uploads a document's related resource.
 * 
 * The resource will be stored in the folder where the document's files
 * reside using the following pattern: <b>fileVersion</b>-<b>suffix</b>
 * 
 * If no version is specified, the current one is used instead
 * 
 * @param request the current request
 * @param docId Id of the document
 * @param suffix Suffix of the document
 * @param fileVersion id of the file version; if null the latest version
 *        will returned
 * @param docVersion id of the doc version; if null the latest version will
 *        returned
 * 
 * @throws Exception a generic error
 */
@SuppressWarnings("unchecked")
public static void uploadDocumentResource(HttpServletRequest request, String docId, String suffix,
		String fileVersion, String docVersion) throws Exception {
	DocumentDAO docDao = (DocumentDAO) Context.get().getBean(DocumentDAO.class);
	Document doc = docDao.findById(Long.parseLong(docId));

	String ver = docVersion;
	if (StringUtils.isEmpty(ver))
		ver = fileVersion;
	if (StringUtils.isEmpty(ver))
		ver = doc.getFileVersion();

	Storer storer = (Storer) Context.get().getBean(Storer.class);

	DiskFileItemFactory factory = new DiskFileItemFactory();
	// Configure the factory here, if desired.
	ServletFileUpload upload = new ServletFileUpload(factory);
	// Configure the uploader here, if desired.
	List<FileItem> fileItems = upload.parseRequest(request);
	for (FileItem item : fileItems) {
		if (!item.isFormField()) {
			File savedFile = File.createTempFile("", "");
			item.write(savedFile);

			InputStream is = null;
			try {
				is = item.getInputStream();
				storer.store(item.getInputStream(), Long.parseLong(docId),
						storer.getResourceName(doc, ver, suffix));
			} finally {
				if (is != null)
					is.close();
				FileUtils.forceDelete(savedFile);
			}
		}
	}
}
 
Example 13
Source File: HelloController.java    From java_study with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/upload")
public String uploadFile(HttpServletRequest request) throws Exception {
    System.out.println("文件上传..");
    // 获取到需要上传文件的路径
    String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
    // 获取file路径,向路径上传文件
    File file = new File(realPath);
    // 判断路径是否存在
    if (!file.exists()) {
        file.mkdirs();
    }
    // 创建磁盘文件工厂方法
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // 解析request对象
    List<FileItem> list = fileUpload.parseRequest(request);
    // 遍历
    for (FileItem item : list) {
        // 判断是普通字段还是文件上传
        if (item.isFormField()) {
        } else {
            // 获取到上传文件的名称
            String fileName = item.getName();
            String uuid = UUID.randomUUID().toString().replace("-","");
            fileName = uuid + "_" + fileName;
            // 上传文件
            item.write(new File(file, fileName));
            // 删除临时文件
            item.delete();
        }
    }
    return "success";
}
 
Example 14
Source File: FileUploader.java    From rebuild with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
	String uploadName = null;
	try {
		List<FileItem> fileItems = parseFileItem(request);
		for (FileItem item : fileItems) {
			uploadName = item.getName();
			if (uploadName == null) {
				continue;
			}

			uploadName = QiniuCloud.formatFileKey(uploadName);
			File file;
			// 上传临时文件
			if (BooleanUtils.toBoolean(request.getParameter("temp"))) {
				uploadName = uploadName.split("/")[2];
				file = SysConfiguration.getFileOfTemp(uploadName);
			} else {
				file = SysConfiguration.getFileOfData(uploadName);
				FileUtils.forceMkdir(file.getParentFile());
			}
			
			item.write(file);
			if (!file.exists()) {
				ServletUtils.writeJson(response, AppUtils.formatControllMsg(1000, "上传失败"));
				return;
			}

			break;
		}
		
	} catch (Exception e) {
		LOG.error(null, e);
		uploadName = null;
	}
	
	if (uploadName != null) {
		ServletUtils.writeJson(response, AppUtils.formatControllMsg(0, uploadName));
	} else {
		ServletUtils.writeJson(response, AppUtils.formatControllMsg(1000, "上传失败"));
	}
}
 
Example 15
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 16
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 17
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 18
Source File: UploadImageFileTemporary.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
  log.debug("Start doPost");
  final PFUserDO user = UserFilter.getUser(request);
  if (user == null) {
    log.warn("Calling of UploadImageFileTemp without logged in user.");
    return;
  }
  // check if the sent request is of the type multi part
  final boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (isMultipart == false) {
    log.warn("The request is not of the type multipart");
    return;
  }
  try { // Parse the request
    final FileItem imgFile = getImgFileItem(request); // get the file item of the multipart request
    // everything ok so far so process the file uploaded
    if (imgFile == null || imgFile.getSize() == 0) {
      log.warn("No file was uploaded, aborting!");
      return;
    }
    if (imgFile.getSize() > MAX_SUPPORTED_FILE_SIZE) {
      log.warn("Maximum file size exceded for file '" + imgFile.getName() + "': " + imgFile.getSize());
      return;
    }
    final File tmpImageFile = ImageCropperUtils.getTempFile(user); // Temporary file
    log.info("Writing tmp file: " + tmpImageFile.getAbsolutePath());
    try {
      // Write new File
      imgFile.write(tmpImageFile);
    } catch (Exception e) {
      log.error("Could not write " + tmpImageFile.getAbsolutePath(), e);
    }
  } catch (FileUploadException ex) {
    log.warn("Failure reading the multipart request");
    log.warn(ex.getMessage(), ex);
  }
  final ServletOutputStream out = response.getOutputStream();
  out.println("text/html");
}
 
Example 19
Source File: UserPictureResource.java    From FoxBPM with Apache License 2.0 4 votes vote down vote up
@Put
@Post
public void update(Representation multipartForm) throws Exception {
	String path = getPath();
	LOG.debug("开始处理上传资源...");
	// 获取参数
	String userId = getAttribute("userId");
	Representation a = getRequest().getEntity();
	System.out.println((multipartForm == a));
	getRequest();
	// 创建上传文件的解析工厂
	DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
	RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);
	if (null != multipartForm) {
		// 获取引擎
		ProcessEngine processEngine = FoxBpmUtil.getProcessEngine();
		// 获取身份服务
		IdentityService identityService = processEngine.getIdentityService();
		UserEntity userEntity = Authentication.selectUserByUserId(userId);
		List<FileItem> fileItems = fileUpload.parseRepresentation(multipartForm);
		String fileName = null;
		String imgName = null;
		for (FileItem fileItem : fileItems) {
			fileName = fileItem.getName();
			if (StringUtil.isEmpty(fileName)) {
				continue;
			}
			LOG.debug("Save image ... " + fileName);
			/* 新建一个图片文件 */
			String extName = fileName.substring(fileName.lastIndexOf("."));
			createDir(path);
			imgName = userId + extName;
			deleteFile(new File(path + userEntity.getImage()));
			File file = new File(path + imgName);
			createFile(file);
			fileItem.write(file);
		}
		userEntity = new UserEntity(userId);
		userEntity.setImage(imgName);
		identityService.updateUser(userEntity);
		CacheUtil.getIdentityCache().remove("user_" + userEntity.getUserId());
	}
}
 
Example 20
Source File: UploadServlet.java    From geofence with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req))
    {

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

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

        File uploadedFile = null;
        // Parse the request
        try
        {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items)
            {
                // process only file upload - discard other form item types
                if (item.isFormField())
                {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null)
                {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        }
        catch (Exception e)
        {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occurred while creating the file : " + e.getMessage());
        }

        try
        {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        }
        catch (Exception exc)
        {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    }
    else
    {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
            "Request contents type is not supported by the servlet.");
    }
}