1. 程式人生 > >Java Web實現圖片上傳並顯示

Java Web實現圖片上傳並顯示

上傳upload.jsp

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <form action="SimpleFileUpload" method="post" enctype="multipart/form-data">
            學號:<input type="text" name="sid"/><br/>
            檔案:<input type="file" name="photo"/><br/>
            <input type="submit" value="上傳"/>
        </form>
    </body>
</html>

上傳servlet

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class SimpleFileUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
            IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //建立DiskFileItemFactory物件,設定緩衝區大小和臨時檔案目錄
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //建立一個檔案上傳解析器ServletFileUpload物件,並設定上傳檔案的大小限制
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            Map<String, List<FileItem>> map = upload.parseParameterMap(request);
            FileItem fileItem = map.get("photo").get(0);
            String photoName = fileItem.getName();
            String sid = map.get("sid").get(0).getString("utf-8");
            InputStream inputStream = fileItem.getInputStream();

            /*在專案中需要對同個檔案流進行兩個操作,
            一個是上傳檔案流到HDFS上,一個是上傳檔案流到solr建立檔案索引,
            將inputStream轉換成ByteArrayOutputStream,
            重複使用流時再用byteArrayOutputStream轉換回來*/
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
            InputStream inputStream1 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            InputStream inputStream2 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

            String path = request.getServletContext().getRealPath("/WEB-INF/img");
            File file = new File(path);
            if (!file.exists() || !file.isDirectory()) {
                file.mkdirs();
            }

            FileOutputStream fileOutputStream =
                    new FileOutputStream(path + File.separator + fileItem.getName());
            byte[] bytes = new byte[512];
            int length;
            while ((length = inputStream1.read(bytes)) > -1) {
                fileOutputStream.write(bytes, 0, length);
            }
            fileOutputStream.flush();
            fileOutputStream.close();

            String sql = "insert into student(sid,photoName,photo)" +
                    " values(?, ?, ?)";
            int rows = DBUtil.update(sql, sid, photoName, inputStream2);
            System.out.println(rows > 0 ? "新增成功" : "新增失敗");
        } catch (FileUploadException | SQLException e) {
            e.printStackTrace();
        }
    }

}

查詢servlet

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Query extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("utf-8");
            String sql = "select sid,photoName,photo FROM student";
            List<Map<String, Object>> data = DBUtil.query(sql);
            req.setAttribute("data", data);
            req.getRequestDispatcher("get").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

查詢頁面idex.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>檔案上傳</title>
    </head>
    <body>
        <table>
            <tr>
                <td>學號</td>
                <td>照片</td>
            </tr>
            <c:forEach items="${requestScope.data}" var="dataMap">
                <tr>
                    <td>${dataMap.sid}</td>
                    <td><img src="img/${dataMap.photoName}" width="120px"/></td>
                </tr>
            </c:forEach>
            <tr>
                <td>
                    <input type="submit" value="修改"/>
                </td>
                <td>
                    <input type="reset" value="重置"/>
                </td>
            </tr>
        </table>
    </body>
</html>