23 September 2016

Upload Image Jsp Servlet Java Web with form Bassic - Java NetBeans

http://localhost:8080/Shop_Bonfire/form.jsp
form.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body><center><h1>Login upload form</h1>
        <form action="Upload" method="POST" enctype="multipart/form-data">
            Username: <br/><input type="text" name="username" value="" /><br/>
            Password <br/><input type="text" name="password" value="" /><br/>
            Photo: <br/><input type="file" name="photo" value="" /><br/>
            <input type="submit" value="Save" />
        </form>
        </center>
    </body>
</html>
formResult.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
    <center>
        <h1>Hello Result!</h1>
        <table border="1" width="250">
                <tr>
                    <td>Username: </td>
                    <td>${username}</td>
                </tr>
                <tr>
                    <td>Password: </td>
                    <td>${password}</td>
                </tr>
                <tr>
                    <td>Photo: </td>
                    <td><img src="images/${fileName}" width="120" height="150"></td>
                </tr>
        </table>
    </center>
    </body>
</html> 
Filter: Upload.java
Java 2016
package controller;

import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 10,
        maxFileSize = 1024 * 1024 * 50,
        maxRequestSize = 1024 * 1024 * 100
)

public class Upload extends HttpServlet {
    private static final long SerialVersionUID = 1L;
    private static final String  UPLOAD_DIR = "images";
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute("username", request.getParameter("username"));
        request.setAttribute("password", request.getParameter("password"));
        request.setAttribute("fileName", uploadFile(request));
        
        request.getRequestDispatcher("formResult.jsp").forward(request, response);
    }
    
    private String uploadFile(HttpServletRequest request) throws IOException, ServletException{
        String fileName="";
        try{
            Part filePart = request.getPart("photo");
            fileName = (String) getFileName(filePart);
            String applicationPath = request.getServletContext().getRealPath("");
            String basePath = applicationPath + File.separator + UPLOAD_DIR + File.separator;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                File outputFilePath = new  File(basePath + fileName);
                inputStream = filePart.getInputStream();
                outputStream = new FileOutputStream(outputFilePath);
                int read = 0;
                final byte[] bytes =  new  byte[1024];
                while((read = inputStream.read(bytes)) != -1){
                    outputStream.write(bytes, 0, read);
                }
            } catch (Exception e) {
                e.printStackTrace();
                fileName = "";
            }finally{
                if(inputStream != null){
                    inputStream.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
            }
            
        }catch(Exception e){
            fileName = "";
        }
        return fileName;
    }
    private String  getFileName(Part part){
        final String  partHeader = part.getHeader("content-disposition");
        System.out.println("*****partHeader :"+ partHeader);
        for(String content : part.getHeader("content-disposition").split(";")){
            if(content.trim().startsWith("filename")){
                return content.substring(content.indexOf('=')+1).trim().replace("\"", "" );
            }
        }
        
        return null;
    }

}
C:\Users\Lonely\Documents\NetBeansProjects\Shop_Bonfire\build\web\images


1 nhận xét:

 

BACK TO TOP

Xuống cuối trang