JSP+java上傳圖片到服務器,並將地址保存至MYSQL + JSP網頁顯示服務器的圖片


這兩天遇到個需求——用戶頭像修改功能。

查了好多資料,不是代碼不全,就是某些高端框架,卡了好久,今已實現,分享給大家,如果有更好的方法,非常感謝可以在下方評論區寫出

 

 

一、整體項目架構

二、web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.runoob.test.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/lianxi/UploadServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <display-name>getImg</display-name>
    <servlet-name>getImg</servlet-name>
    <servlet-class>com.runoob.test.getImg</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getImg</servlet-name>
    <url-pattern>/lianxi/getImg</url-pattern>
  </servlet-mapping>
</web-app>

三、jar包

下載地址

四、JSP文件

 上傳表單——upload.jsp

<%@ page language="java" 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 method="post" action="/lianxi/UploadServlet" enctype="multipart/form-data">
    選擇一個文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上傳" />
</form>


</body>
</html>

上傳完成后的消息提示頁面 + 往session中寫入圖片所在的存儲地址————message.jsp

【可以修改為直接存到數據庫中,然后同步添加至session ——方便后期直接讀取圖片地址,,,由於代碼簡單且繁雜,不屬於核心,故直接用session代替,,,有需要的可以私信】

<%@ page language="java" 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>
<% 
request.setCharacterEncoding("UTF-8");
String logopath =(String) request.getAttribute("logopath");
session.setAttribute("headlogo",logopath);
session.setMaxInactiveInterval(2*60);
%>


<body>
    <center>
        <h2>${message}</h2>
    </center>

    <a href="img.jsp">查看圖片</a>
</body>
</html>

查看圖片頁面————img.jsp

<%@ page language="java" 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>
<%
String imgPath = (String) session.getAttribute("headlogo");
%>
</body>
<img src="/lianxi/getImg?path=<%=imgPath %>">
</html>

 

 

 五、servlet文件+字符串工具類

處理上傳的servlet——UploadServlet.java

package com.runoob.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



import com.runoob.test.tool;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // 上傳文件存儲目錄
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // 上傳配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    /**
     * 上傳數據及保存文件
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // 檢測是否為多媒體上傳
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是則停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表單必須包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // 配置上傳參數
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 設置內存臨界值 - 超過后將產生臨時文件並存儲於臨時目錄中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 設置臨時存儲目錄
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // 設置最大文件上傳值
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // 設置最大請求值 (包含文件和表單數據)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // 中文處理
        upload.setHeaderEncoding("UTF-8"); 

        // 構造臨時路徑來存儲上傳的文件
        // 這個路徑相對當前應用的目錄
        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
       
         
        // 如果目錄不存在則創建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // 解析請求的內容提取文件數據
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // 迭代表單數據
                for (FileItem item : formItems) {
                    // 處理不在表單中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台輸出文件的上傳路徑
                        System.out.println(filePath);                  //原始路徑
                        
                        
                        /*                對存儲的路徑    調用字符串工具  修改*/ tool tl = new tool(); filePath = tl.removeGang(filePath);                         System.out.println(filePath);                 
                        // 保存文件到硬盤
                        
                        item.write(storeFile);
                        request.setAttribute("message",
                            "文件上傳成功!");
                        request.setAttribute("logopath",filePath );                     }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "錯誤信息: " + ex.getMessage());
        }
        // 跳轉到 message.jsp
        getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
    
    
    
        
    }

字符串工具類——tool.java

package com.runoob.test;

public class tool {
    public String removeGang(String xx) {
        xx = xx.replaceAll("\\\\", "/");    //為什么這么寫?可以看下UploadServlet.java 上傳圖片的存儲路徑:xxx\xxxx\xxxxx\xxx\xx   為了將該圖片從服務器中讀取出來,需要通過url地址來訪問,然鵝“\“是非法url編碼,需要變為”/"
        System.out.println(xx);
        return xx;
    }
}

輸出圖片————getImg.java

package com.runoob.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

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

/**
 * Servlet implementation class getImg
 */
@WebServlet("/getImg")
public class getImg extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public getImg() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
               String pathName = request.getParameter("path");             File imgFile = new File(pathName);
            FileInputStream fin = null;
            OutputStream output = null;
            try {
                output = response.getOutputStream();
                fin = new FileInputStream(imgFile);
                byte[] arr = new byte[1024*10];
                int n;
                while((n = fin.read(arr)) != -1) {
                    output.write(arr,0,n);
                }
                output.flush();
                System.out.println("圖像輸出完畢");
                }catch(IOException e) {
                    e.printStackTrace();
                }
                try {
                    output.close();
                }catch(IOException e) {
                    e.printStackTrace();
                }
                
            }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

    
    
}

然后就可以直接 <img src="/lainxi/getImg?path=存儲路徑"  class=”CSS類">

如img.jsp

 

 

 

 

原理后期補充,先趕火車......

 

 

 

 

演示:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM