Java Code Examples for javax.servlet.http.Part#write()

The following examples show how to use javax.servlet.http.Part#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: UploadServlet.java    From psychoPATH with GNU General Public License v3.0 6 votes vote down vote up
/**
    * handles file upload
    */
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // gets absolute path of the web application
       String appPath = request.getServletContext().getRealPath("");
       // constructs path of the directory to save uploaded file
// appPath + File.separator
       String savePath =  SAVE_DIR;
        
       // creates the save directory if it does not exists
       File fileSaveDir = new File(savePath);
       if (!fileSaveDir.exists()) {
           fileSaveDir.mkdir(); 
       }
       String full_name=SAVE_DIR;
       for (Part part : request.getParts()) {
           String fileName = extractFileName(part);
           part.write(savePath + File.separator + fileName);
    full_name=savePath + File.separator + fileName;
       }

       request.setAttribute("message", "Upload has been done successfully!");
       getServletContext().getRequestDispatcher("/message.jsp").forward(
               request, response);
   }
 
Example 2
Source File: UploadServlet.java    From psychoPATH with GNU General Public License v3.0 6 votes vote down vote up
/**
    * handles file upload
    */
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // gets absolute path of the web application
       String appPath = request.getServletContext().getRealPath("");
       // constructs path of the directory to save uploaded file
// appPath + File.separator
       String savePath =  SAVE_DIR;
        
       // creates the save directory if it does not exists
       File fileSaveDir = new File(savePath);
       if (!fileSaveDir.exists()) {
           fileSaveDir.mkdir(); 
       }
       String full_name=SAVE_DIR;
       for (Part part : request.getParts()) {
           String fileName = extractFileName(part);
    fileName=fileName.replaceAll("\\.\\.","");
           part.write(savePath + File.separator + fileName);
    full_name=savePath + File.separator + fileName;
       }

       request.setAttribute("message", "Upload has been done successfully!");
       getServletContext().getRequestDispatcher("/message.jsp").forward(
               request, response);
   }
 
Example 3
Source File: UploadServlet.java    From psychoPATH with GNU General Public License v3.0 6 votes vote down vote up
/**
    * handles file upload
    */
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // gets absolute path of the web application
       String appPath = request.getServletContext().getRealPath("");
       // constructs path of the directory to save uploaded file
// appPath + File.separator
       String savePath =  SAVE_DIR;
        
       // creates the save directory if it does not exists
       File fileSaveDir = new File(savePath);
       if (!fileSaveDir.exists()) {
           fileSaveDir.mkdir(); 
       }
       String full_name=SAVE_DIR;
       for (Part part : request.getParts()) {
           String fileName = extractFileName(part);
           part.write(savePath + File.separator + fileName);
    full_name=savePath + File.separator + fileName;
       }

       request.setAttribute("message", "Upload has been done successfully!");
       getServletContext().getRequestDispatcher("/message.jsp").forward(
               request, response);
   }
 
Example 4
Source File: FileUploadServlet.java    From journaldev with MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
     
    // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }
    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
    
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        part.write(uploadFilePath + File.separator + fileName);
    }
 
    request.setAttribute("message", fileName + " File uploaded successfully!");
    getServletContext().getRequestDispatcher("/response.jsp").forward(
            request, response);
}
 
Example 5
Source File: UserAvatarServlet.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	ServletHelper helper = new ServletHelper(request,response);
	int uid = helper.getInt("uid");
	Part part = helper.getPart("avatar");
	if (part != null) {
           part.write(getServletContext().getRealPath(
                   "/photo/avatar") + "/" + uid + ".jpg");
       }
	if(part != null){
		helper.put("response", "user_avatar");
	}else{
		helper.put("response", "error");
		Map<String , Object> outMap = new HashMap<String , Object>() ;
		outMap.put("text", "头像上传错误");
		helper.put("error",outMap);
	}
	helper.send();
}
 
Example 6
Source File: MultipartServlet.java    From tutorials with MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists())
            uploadDir.mkdir();

        try {
            String fileName = "";
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                part.write(uploadPath + File.separator + fileName);
            }
            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
        } catch (FileNotFoundException fne) {
            request.setAttribute("message", "There was an error: " + fne.getMessage());
        }
        getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
    }
 
Example 7
Source File: ApplicantResourceController.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@CsrfProtected
@ServeResourceMethod(portletNames = { "portlet1" }, resourceID = "uploadFiles")
@ValidateOnExecution(type = ExecutableType.NONE)
public void uploadFiles(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {

	PortletSession portletSession = resourceRequest.getPortletSession(true);
	List<Attachment> attachments = attachmentManager.getAttachments(portletSession.getId());

	try {
		Collection<Part> transientMultipartFiles = resourceRequest.getParts();

		if (!transientMultipartFiles.isEmpty()) {

			File attachmentDir = attachmentManager.getAttachmentDir(portletSession.getId());

			if (!attachmentDir.exists()) {
				attachmentDir.mkdir();
			}

			for (Part transientMultipartFile : transientMultipartFiles) {

				String submittedFileName = transientMultipartFile.getSubmittedFileName();

				if (submittedFileName != null) {
					File copiedFile = new File(attachmentDir, submittedFileName);

					transientMultipartFile.write(copiedFile.getAbsolutePath());

					attachments.add(new Attachment(copiedFile));
				}
			}

			_writeTabularJSON(resourceResponse.getWriter(), attachments);
		}
	}
	catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
}
 
Example 8
Source File: ApplicantResourceController.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@CsrfProtected
@ServeResourceMethod(portletNames = { "portlet1" }, resourceID = "uploadFiles")
@ValidateOnExecution(type = ExecutableType.NONE)
public void uploadFiles(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {

	PortletSession portletSession = resourceRequest.getPortletSession(true);
	List<Attachment> attachments = attachmentManager.getAttachments(portletSession.getId());

	try {
		Collection<Part> transientMultipartFiles = resourceRequest.getParts();

		if (!transientMultipartFiles.isEmpty()) {

			File attachmentDir = attachmentManager.getAttachmentDir(portletSession.getId());

			if (!attachmentDir.exists()) {
				attachmentDir.mkdir();
			}

			for (Part transientMultipartFile : transientMultipartFiles) {

				String submittedFileName = transientMultipartFile.getSubmittedFileName();

				if (submittedFileName != null) {
					File copiedFile = new File(attachmentDir, submittedFileName);

					transientMultipartFile.write(copiedFile.getAbsolutePath());

					attachments.add(new Attachment(copiedFile));
				}
			}

			_writeTabularJSON(resourceResponse.getWriter(), attachments);
		}
	}
	catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
}
 
Example 9
Source File: UploadCustomerDocumentsServlet.java    From tutorials with MIT License 5 votes vote down vote up
protected void doPost(
 HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
        part.write("myFile");
    }
  
    PrintWriter writer = response.getWriter();
    writer.println("<html>File uploaded successfully!</html>");
    writer.flush();
}
 
Example 10
Source File: HTMLManagerServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";

    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename = warPart.getSubmittedFileName();
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('/') + 1);
            }

            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(host.getAppBaseFile(), filename);
            if (file.exists()) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadWarExists",
                        filename);
                break;
            }

            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();

            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadInServerXml",
                        filename);
                break;
            }

            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch(Exception e) {
        message = smClient.getString
            ("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
 
Example 11
Source File: UploadMutation.java    From samples with MIT License 4 votes vote down vote up
boolean upload(Part part) throws IOException {
  log.info("Part: {}", part.getSubmittedFileName());
  part.write(part.getSubmittedFileName());
  return true;
}
 
Example 12
Source File: HTMLManagerServlet.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";

    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename =
                extractFilename(warPart.getHeader("Content-Disposition"));
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('/') + 1);
            }

            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(deployed, filename);
            if (file.exists()) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadWarExists",
                        filename);
                break;
            }
            
            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();

            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadInServerXml",
                        filename);
                break;
            }

            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch(Exception e) {
        message = smClient.getString
            ("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
 
Example 13
Source File: FileUploadServlet.java    From Tutorials with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");

	// gets absolute path of the web application
	String applicationPath = request.getServletContext().getRealPath("");
	// constructs path of the directory to save uploaded file
	String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

	// creates upload folder if it does not exists
	File uploadFolder = new File(uploadFilePath);
	if (!uploadFolder.exists()) {
		uploadFolder.mkdirs();
	}

	PrintWriter writer = response.getWriter();

	// write all files in upload folder
	for (Part part : request.getParts()) {
		if (part != null && part.getSize() > 0) {
			String fileName = part.getSubmittedFileName();
			String contentType = part.getContentType();
			
			// allows only JPEG files to be uploaded
			if (!contentType.equalsIgnoreCase("image/jpeg")) {
				continue;
			}
			
			part.write(uploadFilePath + File.separator + fileName);
			
			writer.append("File successfully uploaded to " 
					+ uploadFolder.getAbsolutePath() 
					+ File.separator
					+ fileName
					+ "<br>\r\n");
		}
	}

}
 
Example 14
Source File: HTMLManagerServlet.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";

    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename =
                extractFilename(warPart.getHeader("Content-Disposition"));
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('/') + 1);
            }

            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(deployed, filename);
            if (file.exists()) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadWarExists",
                        filename);
                break;
            }
            
            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();

            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadInServerXml",
                        filename);
                break;
            }

            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch(Exception e) {
        message = smClient.getString
            ("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
 
Example 15
Source File: UploadUtils.java    From HotelSystem with Apache License 2.0 3 votes vote down vote up
/**
 * 用于上传一个文件,返回该文件的文件名
 *
 * @return String 存储的文件名
 * @name
 * @notice none
 * @author <a href="mailto:[email protected]">黄钰朝</a>
 * @date 2019/4/19
 */
public static String upload(Part part) throws IOException {
    String head = part.getHeader("Content-Disposition");
    String filename = getUUID() + head.substring(head.lastIndexOf("."), head.lastIndexOf("\""));
    part.write(filename);
    return filename;
}