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

The following examples show how to use org.apache.commons.fileupload.FileItem#getName() . 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: FileUploadService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return the file name, without its whole path, from the file item. This should be used has FileItem.getName can return the whole path.
 * 
 * @param fileItem
 *            the fileItem to process
 * @return the name of the file associated
 */
public static String getFileNameOnly( FileItem fileItem )
{
    String strFileName;

    if ( fileItem != null )
    {
        strFileName = fileItem.getName( );

        if ( strFileName != null )
        {
            strFileName = FilenameUtils.getName( strFileName );
        }
    }
    else
    {
        strFileName = null;
    }

    return strFileName;
}
 
Example 2
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 3
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 4
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 5
Source File: AvatarUploadController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {

    String username = securityService.getCurrentUsername(request);

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

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

    // Look for file items.
    for (FileItem item : items) {
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

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

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult","model",map);
}
 
Example 6
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 7
Source File: ClassifyUtils.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) {
  // Handle file upload
  String contentType = request.getHeader("content-type");
  // out.write("CT: " + contentType + " " + tm + " " + id);
  if (contentType != null && contentType.startsWith("multipart/form-data")) {
    try {
      FileUpload upload = new FileUpload(new DefaultFileItemFactory());
      for (FileItem item : upload.parseRequest(request)) {
        if (item.getSize() > 0) {
          // ISSUE: could make use of content type if known
          byte[] content = item.get();
          ClassifiableContent cc = new ClassifiableContent();
          String name = item.getName();
          if (name != null)
            cc.setIdentifier("fileupload:name:" + name);
          else
            cc.setIdentifier("fileupload:field:" + item.getFieldName());              
          cc.setContent(content);
          return cc;
        }      
      }
    } catch (Exception e) {
      throw new OntopiaRuntimeException(e);
    }
  }
  return null;
}
 
Example 8
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 9
Source File: ImpDocXML.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField())
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
String CurrFold=getActFolderId(Req);
DriverGeneric PDSession=SParent.getSessOPD(Req);  
int Tot=PDSession.ProcessXMLB64(FileData, CurrFold);
FileData.close();
out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot));
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 10
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 11
Source File: SyllabusTool.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String processUpload(ValueChangeEvent event)
{
  if(attachCaneled == false)
  {
    Object newValue = event.getNewValue();

    if (newValue instanceof String) return "";
    if (newValue == null) return "";

    FileItem item = (FileItem) event.getNewValue();
    try (InputStream inputStream = item.getInputStream())
    {
      String fileName = item.getName();

      ResourcePropertiesEdit props = contentHostingService.newResourceProperties();

      if (fileName != null) {
          filename = FilenameUtils.getName(filename);
      }

      ContentResourceEdit thisAttach = contentHostingService.addAttachmentResource(fileName);
      thisAttach.setContent(inputStream);
      thisAttach.setContentType(item.getContentType());
      thisAttach.getPropertiesEdit().addAll(props);
      contentHostingService.commitResource(thisAttach);
      
      SyllabusAttachment attachObj = syllabusManager.createSyllabusAttachmentObject(thisAttach.getId(), fileName);
      attachments.add(attachObj);

      if(entry.justCreated != true)
      {
        allAttachments.add(attachObj);
      }
    }
    catch (Exception e)
    {
      log.error(this + ".processUpload() in SyllabusTool", e);
    }
    if(entry.justCreated == true)
    {
      return "edit";
    }
    else
    {
      return "read";
    }
  }
  return null;
}
 
Example 12
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 13
Source File: ImportThesF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);  
    String NewThesId=ListFields.get("ThesNum");
    String ThesName=ListFields.get("ThesName");
    String RootText=ListFields.get("RootText");
    String MainLanguage=ListFields.get("MainLanguage");
    String SubByLang=ListFields.get("SubByLang");
    String Transact=ListFields.get("Transact");
    String RetainCodes=ListFields.get("RetainCodes");
    DriverGeneric PDSession = getSessOPD(Req); 
    PDThesaur Thes=new PDThesaur(PDSession);
    Thes.Import(ThesName, NewThesId, FileData, MainLanguage, RootText, SubByLang.equals("1"), Transact.equals("1"), RetainCodes.equals("1"));
    FileData.close();
    out.println(UpFileStatus.SetResultOk(Req, Thes.getImportReport()));
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 14
Source File: ModDocF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);  
    PDDocs Doc;
    DriverGeneric PDSession = getSessOPD(Req); 
    String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
    if (DType==null)
        Doc = new PDDocs(PDSession);
    else
        Doc = new PDDocs(PDSession, DType);
    Doc.LoadFull((String) ListFields.get(PDDocs.fPDID));
    Record Rec=Doc.getRecSum();
    Rec.initList();
    Attribute Attr=Rec.nextAttr();
    while (Attr!=null)
        {
        if (!List.contains(Attr.getName()))
            {
            String Val=(String) ListFields.get(Attr.getName());
            if (Attr.getType()==Attribute.tBOOLEAN)
                {
                if(Val == null || Val.length()==0 || Val.equals("0"))
                    Attr.setValue(false);
                else
                    Attr.setValue(true);
                }
            else if(Val != null)
                {
                SParent.FillAttr(Req, Attr, Val, false);
                }
            }
        Attr=Rec.nextAttr();
        }
    Doc.assignValues(Rec);
    Doc.setParentId(ListFields.get("CurrFold"));
    Doc.setName(FileName);   
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    Doc.update();
    out.println(UpFileStatus.SetResultOk(Req, ""));
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
finally
    {
    out.close();    
    }
}
 
Example 15
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.");
    }
}
 
Example 16
Source File: AttachmentServlet.java    From swellrt with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
  // Process only multipart requests.
  if (ServletFileUpload.isMultipartContent(request)) {
    // Create a factory for disk-based file items.
    FileItemFactory factory = new DiskFileItemFactory();

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

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

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

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

      String fileName = fileItem.getName();
      // Get only the file name not whole path.
      if (fileName != null) {
        fileName = FilenameUtils.getName(fileName);
        service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
        response.setStatus(HttpServletResponse.SC_CREATED);
        String msg =
            String.format("The file with name: %s and id: %s was created successfully.",
                fileName, id);
        LOG.fine(msg);
        response.getWriter().print("OK");
        response.flushBuffer();
      }
    } catch (Exception e) {
      LOG.severe("Upload error", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "An error occurred while upload the file : " + e.getMessage());
    }
  } else {
    LOG.severe("Request contents type is not supported by the servlet.");
    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        "Request contents type is not supported by the servlet.");
  }
}
 
Example 17
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 18
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 19
Source File: SyllabusTool.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String processUpload(ValueChangeEvent event)
{
  if(attachCaneled == false)
  {
    Object newValue = event.getNewValue();

    if (newValue instanceof String) return "";
    if (newValue == null) return "";

    FileItem item = (FileItem) event.getNewValue();
    try (InputStream inputStream = item.getInputStream())
    {
      String fileName = item.getName();

      ResourcePropertiesEdit props = contentHostingService.newResourceProperties();

      if (fileName != null) {
          filename = FilenameUtils.getName(filename);
      }

      ContentResourceEdit thisAttach = contentHostingService.addAttachmentResource(fileName);
      thisAttach.setContent(inputStream);
      thisAttach.setContentType(item.getContentType());
      thisAttach.getPropertiesEdit().addAll(props);
      contentHostingService.commitResource(thisAttach);
      
      SyllabusAttachment attachObj = syllabusManager.createSyllabusAttachmentObject(thisAttach.getId(), fileName);
      attachments.add(attachObj);

      if(entry.justCreated != true)
      {
        allAttachments.add(attachObj);
      }
    }
    catch (Exception e)
    {
      log.error(this + ".processUpload() in SyllabusTool", e);
    }
    if(entry.justCreated == true)
    {
      return "edit";
    }
    else
    {
      return "read";
    }
  }
  return null;
}
 
Example 20
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, "上传失败"));
	}
}