Tuesday 29 July 2014

File Upload : getPart (String name)

public Part getPart(String name) throws IOException, ServletException
Gets the Part with the given name. The part represents a part or form item that was received within a multipart/form-data POST request. Part provides access to the headers, content type related with it and also the content via getInputStream method.

Form tag
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

If enctype is multipart/form-data, No characters are encoded. This value is required when you are using forms that have a file upload control.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="/servlet/FileUpload" enctype="multipart/form-data" >
            <table>
                <tr>
                    File:<input type="file" name="file" id="file" /><br />
                </tr>
                <tr>
                    Destination:<input type="text" name="destination"/><br />
                </tr>
                <tr>
                    <input type="submit" value="Upload" name="upload" id="upload" />
                </tr>
            </table>
        </form>
    </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>FileUpload</servlet-name>
        <servlet-class>FileUpload</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>FileUpload</servlet-name>
        <url-pattern>/FileUpload</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.annotation.*;

@MultipartConfig
public class FileUpload extends HttpServlet {
     
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");

        final PrintWriter writer = response.getWriter();
         
        // Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;

        try {
            out = new FileOutputStream(new File(path + File.separator+ fileName));
            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + path);
            
        } 
        catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());
        } 
        finally 
        {
            if (out != null) {
                out.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }
  
    private String getFileName(final Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
  
}

Output








Prevoius                                                 Next                                                 Home

No comments:

Post a Comment