2017年8月9日 星期三

20170810 [JAVA] Form上傳圖片與文字

STEP 0(前置作業): 下載所需Jar檔
1. jspsmart.jar
2. commons-fileupload-1.3.3.jar
3. commons-io-2.5.jar


STEP 1: 檔案配置
先把剛剛步驟0的jar檔放到lib下























STEP 2 : 程式碼如下

(1) UploadServlet

package servlet;



import java.io.File;
import java.io.IOException;

import javax.servlet.ServletConfig;
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 com.jspsmart.upload.SmartUpload;



@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L;
    private ServletConfig config;

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

      doPost(request, response);
    }

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



        // 建立一個SmartUpload類別
        SmartUpload mySmartUpload = new SmartUpload();

        

        // 建立新路徑
        // 取得文件的上傳實際目錄,也就是你的web項目真實路徑
        String realPath = request.getSession().getServletContext().getRealPath("/");

        // 定義上傳目錄
        String dirPath = realPath+"uploadPhoto";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()) // 如果此路徑不存在則建立此路徑
            dirFile.mkdirs();



        try {
            // 初始化
            mySmartUpload.initialize(config, request, response);

            // 上傳
            mySmartUpload.upload();
            for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
                com.jspsmart.upload.File myfile = mySmartUpload.getFiles().getFile(i);
                String fileName = myfile.getFileName();
                // System.out.println("fileName:" + fileName);
                // 保存
                mySmartUpload.save(dirPath);
            }
        } catch (Exception e) {
            System.out.println("e:" + e);
        }

        // 取得非file類型的值
        String myText = mySmartUpload.getRequest().getParameter("myText"); 
        System.out.println("取得前端的值myText:" + myText);
        System.out.println("圖片存放的路徑:" + dirPath);

        request.setAttribute("message", "上傳成功");
        // 跳轉頁面 message.jsp
        request.getRequestDispatcher("/message.jsp").forward(request, response);

    }
    final public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }
}


(2) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="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>servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/Demo_UploadPhotoForm/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>


(3) index.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>
<h1>文件上傳</h1>
<form method="post" action="/Demo_UploadPhotoForm/UploadServlet" enctype="multipart/form-data">
            輸入文字:<input type="text" name="myText" value="Hello"><br/><br/>
            選擇上傳文件:
    <input type="file" name="uploadFile" size="20" />
    <br/><br/>
    <input type="hidden" name="action" value="hello">
    <input type="submit" value="上傳" />
</form>
</body>
</html>


(4) message.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>
        <center>
            <h2>${message}</h2>
        </center>
    </body>
</html>
//參考文件
(1) http://www.massapi.com/source/github/18/49/1849710875/src/com/common/tool/ServletUpload.java.html#40
(2) http://www.jianshu.com/p/1be823db9882
(3) http://fanli7.net/a/bianchengyuyan/C__/20120822/209893.html
(4) http://www.jb51.net/web/165444.html

沒有留言:

張貼留言

20200826 [日記] 前後前後前前後後

人生也需要管理 by工作上的前輩 問題不管怎樣一定會解決,只是是好的解法還是壞的解法 by工作上的廠商 以上是最近常常徘徊在心頭的小標語。 1. 一直覺得業務是沒有專業能力才會做的職業,但最近真的打從心底的小小改觀。 2. 工作上還是很多讓人不耐煩的事情,但越來越能面對它處理它放...