1. 程式人生 > >webuploader上傳圖片

webuploader上傳圖片

1.將資料夾修改成名字為webuploader 直接放在WebContent下

2.將examples/image-upload/index.html 複製一份到WebContent下並修改檔案中引用的css/js的資源路徑

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>WebUploader演示</title>
    <link rel="stylesheet" type="text/css" href="webuploader/css/webuploader.css" />
    <link rel="stylesheet" type="text/css" href="webuploader/examples/image-upload/style.css" />
</head>
<body>
    <div id="wrapper">
        <div id="container">
            <!--頭部,相簿選擇和格式選擇-->
            <div id="uploader">
                <div class="queueList">
                    <div id="dndArea" class="placeholder">
                        <div id="filePicker"></div>
                        <p>或將照片拖到這裡,單次最多可選300張</p>
                    </div>
                </div>
                <div class="statusBar" style="display:none;">
                    <div class="progress">
                        <span class="text">0%</span>
                        <span class="percentage"></span>
                    </div><div class="info"></div>
                    <div class="btns">
                        <div id="filePicker2"></div><div class="uploadBtn">開始上傳</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="webuploader/examples/image-upload/jquery.js"></script>
    <script type="text/javascript" src="webuploader/dist/webuploader.js"></script>
    <script type="text/javascript" src="webuploader/examples/image-upload/upload.js"></script>
</body>
</html>

3.在upload.js中修改檔案上傳的路徑

4.編寫後臺程式碼

本文以servlet為例,程式碼如下:

package com.lq.webUploader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 設定檔案上傳路徑  D:/apache-tomcat-6.0.35/webapps/upload/WEB-INF/upload
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
		File file = new File(savePath);
		// 判斷上傳檔案的儲存目錄是否存在
		if (!file.exists()) {
			// 建立目錄
			file.mkdir();
		}
		// 訊息提示
		String message = "";
		try {
			// 使用Apache檔案上傳元件處理檔案上傳步驟:
			// 1、建立一個DiskFileItemFactory工廠
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2、建立一個檔案上傳解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解決上傳檔名的中文亂碼
			upload.setHeaderEncoding("UTF-8");
			// 3、 檢測是否為多媒體上傳
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照傳統方式獲取資料
				return;
			}
			// 4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,
			//每一個FileItem對應一個Form表單的輸入項
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				// 如果fileitem中封裝的是普通輸入項的資料
				if (item.isFormField()) {
					String name = item.getFieldName();
					// 解決普通輸入項的資料的中文亂碼問題
					String value = item.getString("UTF-8");
					//System.out.println(name + "=" + value);
				} else {
					// 如果fileitem中封裝的是上傳檔案得到上傳的檔名稱,
					String filename = item.getName();					
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					filename = filename.substring(filename.lastIndexOf("\\") + 1);
					// 建立一個檔案輸出流
					FileOutputStream out = new FileOutputStream(savePath + "\\"+ filename);
					// 獲取item中的上傳檔案的輸入流
					InputStream in = item.getInputStream();
					// 建立一個緩衝區
					byte buffer[] = new byte[1024];
					// 判斷輸入流中的資料是否已經讀完的標識
					int len = 0;
					// 迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料
					while ((len = in.read(buffer)) > 0) {
						out.write(buffer, 0, len);
					}
					// 關閉輸入流
					in.close();
					// 關閉輸出流
					out.close();
					message = "檔案上傳成功!";
					response.setCharacterEncoding("utf-8");
					response.getWriter().write(message);
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

5.測試