Javax.servlet.http.Part to java.io.File

I need help with the code that is used to convert javax.servlet.http.Part to java.io.File

I found this useful code, but I need help with the correct implementation of the code.

private void processFilePart(Part part, String filename) throws IOException
    {
        filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
        String prefix = filename;
        String suffix = "";
        if (filename.contains("."))
        {
            prefix = filename.substring(0, filename.lastIndexOf('.'));
            suffix = filename.substring(filename.lastIndexOf('.'));
        }
        File file = File.createTempFile(prefix + "_", suffix, new File(location));
        if (multipartConfigured)
        {
            part.write(file.getName());
        }
        else
        {
            InputStream input = null;
            OutputStream output = null;
            try
            {
                input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE);
                output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE);
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                for (int length = 0; ((length = input.read(buffer)) > 0);)
                {
                    output.write(buffer, 0, length);
                }
            }
            finally
            {
                if (output != null)
                    try
                    {
                        output.close();
                    }
                    catch (IOException logOrIgnore)
                    {
                    }
                if (input != null)
                    try
                    {
                        input.close();
                    }
                    catch (IOException logOrIgnore)
                    {
                    }
            }
        }
        put(part.getName(), file);
        part.delete();
    }

I tried to edit the code to create as a result of java.io.File, but I always have problems.

private void processFilePart(Part part, String filename) throws IOException
    {
        int DEFAULT_BUFFER_SIZE = 2048;

        filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
        String prefix = filename;
        String suffix = "";
        if (filename.contains("."))
        {
            prefix = filename.substring(0, filename.lastIndexOf('.'));
            suffix = filename.substring(filename.lastIndexOf('.'));
        }
        File file = new File(filename);
        InputStream input = null;
        OutputStream output = null;
        try
        {
            input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE);
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            for (int length = 0; ((length = input.read(buffer)) > 0);)
            {
                output.write(buffer, 0, length);
            }
        }
        finally
        {
            if (output != null)
                try
                {
                    output.close();
                }
                catch (IOException logOrIgnore)
                {
                }
            if (input != null)
                try
                {
                    input.close();
                }
                catch (IOException logOrIgnore)
                {
                }
        }

        // how to get the result

        part.delete();
    }

What is the correct way to transform objects?

+4
source share
1 answer

File upload example application - taken from http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

The file upload example shows how to implement and use the file upload function.

The sample file upload application consists of a single servlet and an HTML form that makes a request to download a file with a servlet.

​​ HTML- " ". , , , . , POST. :

enctype multipart/form-data.

POST.

, . . - , . "" , .

HTML- tut-install/examples/web/fileupload/web/index.html :

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="upload" enctype="multipart/form-data" >
            File:
            <input type="file" name="file" id="file" /> <br/>
            Destination:
            <input type="text" value="/tmp" name="destination"/>
            </br>
            <input type="submit" value="Upload" name="upload" id="upload" />
        </form>
    </body>
</html>

POST , , , . , GET URL- , POST . . POST - bodys.

, , , . .

fileupload sample.txt , tmp :

POST /fileupload/upload HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-data; 
boundary=---------------------------263081694432439
Content-Length: 441
-----------------------------263081694432439
Content-Disposition: form-data; name="file"; filename="sample.txt"
Content-Type: text/plain

Data from sample file
-----------------------------263081694432439
Content-Disposition: form-data; name="destination"

/tmp
-----------------------------263081694432439
Content-Disposition: form-data; name="upload"

Upload
-----------------------------263081694432439--

FileUploadServlet.java tut-install/examples/web/fileupload/src/java/fileupload/. :

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());

@WebServlet urlPatterns .

@MultipartConfig , , MIME / .

processRequest , getFileName . FileOutputStream . , . processRequest getFileName :

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // 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;
    final PrintWriter writer = response.getWriter();

    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);
        LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
                new Object[]{fileName, 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());

        LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
                new Object[]{fne.getMessage()});
    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}
+5

All Articles