国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java基礎篇---文件上傳(smartupload組件)

2019-11-14 22:38:34
字體:
來源:轉載
供稿:網友
java基礎篇---文件上傳(smartupload組件)

文件上傳幾乎是所有網站都具有的功能,用戶可以將文件上傳到服務器的指定文件夾中,也可以保存在數據庫中,本篇主要說明smartupload組件上傳。

在講解smartupload上傳前,我們先來看看不使用組件是怎么完成上傳的原理的?

廢話不多說直接上代碼

import java.io.*;import java.util.*;import javax.servlet.http.HttpServletRequest;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;public class FileUploadTools {    PRivate HttpServletRequest request = null; // 取得HttpServletRequest對象    private List<FileItem> items = null; // 保存全部的上傳內容    private Map<String, List<String>> params = new HashMap<String, List<String>>();    // 保存所有的參數    private Map<String, FileItem> files = new HashMap<String, FileItem>();    private int maxSize = 3145728;                 // 默認的上傳文件大小為3MB,3 * 1024 * 1024    public FileUploadTools(HttpServletRequest request, int maxSize,            String tempDir) throws Exception {    // 傳遞request對象、最大上傳限制、臨時保存目錄        this.request = request;                 // 接收request對象        DiskFileItemFactory factory = new DiskFileItemFactory(); // 創建磁盤工廠        if (tempDir != null) {                     // 判斷是否需要進行臨時上傳目錄            factory.setRepository(new File(tempDir)); // 設置臨時文件保存目錄        }        ServletFileUpload upload = new ServletFileUpload(factory); // 創建處理工具        if (maxSize > 0) {                        // 如果給的上傳大小限制大于0,則使用新的設置            this.maxSize = maxSize;        }        upload.setFileSizeMax(this.maxSize);     // 設置最大上傳大小為3MB,3 * 1024 * 1024        try {            this.items = upload.parseRequest(request);// 接收全部內容        } catch (FileUploadException e) {            throw e;                             // 向上拋出異常        }        this.init();                             // 進行初始化操作    }    private void init() {                        // 初始化參數,區分普通參數或上傳文件        Iterator<FileItem> iter = this.items.iterator();        ipTimeStamp its = new IPTimeStamp(this.request.getRemoteAddr()) ;        while (iter.hasNext()) {                // 依次取出每一個上傳項            FileItem item = iter.next();         // 取出每一個上傳的文件            if (item.isFormField()) {             // 判斷是否是普通的文本參數                String name = item.getFieldName(); // 取得表單的名字                String value = item.getString(); // 取得表單的內容                List<String> temp = null;         // 保存內容                if (this.params.containsKey(name)) { // 判斷內容是否已經存放                    temp = this.params.get(name); // 如果存在則取出                } else {                        // 不存在                    temp = new ArrayList<String>(); // 重新開辟List數組                }                temp.add(value);                 // 向List數組中設置內容                this.params.put(name, temp);     // 向Map中增加內容            } else {                             // 判斷是否是file組件                String fileName = its.getIPTimeRand()                    + "." + item.getName().split("http://.")[1];                this.files.put(fileName, item); // 保存全部的上傳文件            }        }    }    public String getParameter(String name) {     // 取得一個參數        String ret = null;                         // 保存返回內容        List<String> temp = this.params.get(name); // 從集合中取出內容        if (temp != null) {                        // 判斷是否可以根據key取出內容            ret = temp.get(0);                     // 取出里面的內容        }        return ret;    }    public String[] getParameterValues(String name) { // 取得一組上傳內容        String ret[] = null;                     // 保存返回內容        List<String> temp = this.params.get(name); // 根據key取出內容        if (temp != null) {                        // 避免NullPointerException            ret = temp.toArray(new String[] {});// 將內容變為字符串數組        }        return ret;                             // 變為字符串數組    }    public Map<String, FileItem> getUploadFiles() {// 取得全部的上傳文件        return this.files;                         // 得到全部的上傳文件    }    public List<String> saveAll(String saveDir) throws IOException { // 保存全部文件,并返回文件名稱,所有異常拋出        List<String> names = new ArrayList<String>();        if (this.files.size() > 0) {            Set<String> keys = this.files.keySet(); // 取得全部的key            Iterator<String> iter = keys.iterator(); // 實例化Iterator對象            File saveFile = null;                 // 定義保存的文件            InputStream input = null;             // 定義文件的輸入流,用于讀取源文件            OutputStream out = null;             // 定義文件的輸出流,用于保存文件            while (iter.hasNext()) {            // 循環取出每一個上傳文件                FileItem item = this.files.get(iter.next()); // 依次取出每一個文件                String fileName = new IPTimeStamp(this.request.getRemoteAddr())                        .getIPTimeRand()                        + "." + item.getName().split("http://.")[1];                saveFile = new File(saveDir + fileName);     // 重新拼湊出新的路徑                names.add(fileName);            // 保存生成后的文件名稱                try {                    input = item.getInputStream();             // 取得InputStream                    out = new FileOutputStream(saveFile);     // 定義輸出流保存文件                    int temp = 0;                            // 接收每一個字節                    while ((temp = input.read()) != -1) {     // 依次讀取內容                        out.write(temp);         // 保存內容                    }                } catch (IOException e) {         // 捕獲異常                    throw e;                    // 異常向上拋出                } finally {                     // 進行最終的關閉操作                    try {                        input.close();            // 關閉輸入流                        out.close();            // 關閉輸出流                    } catch (IOException e1) {                        throw e1;                    }                }            }        }        return names;                            // 返回生成后的文件名稱    }}

上面代碼便可以完成無組件上傳。

下面開始講解smartupload

smartupload是由www.jspsmart.com網站開發的一套上傳組件包,可以輕松的實現文件的上傳及下載功能,smartupload組件使用簡單、可以輕松的實現上傳文件類型的限制、也可以輕易的取得上傳文件的名稱、后綴、大小等。smartupload本身是一個系統提供的jar包(smartupload.jar),用戶直接將此包放到classpath下即可,也可以直接將此包拷貝到TOMCAT_HOME/lib目錄之中。下面使用組件完成上傳單一文件上傳:
<html><head><title>smartupload組件上傳</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">    圖片<input type="file" name="pic">    <input type="submit" value="上傳"></form></body></html>

jsp代碼:

smartupload_demo01.jsp
<%@ page contentType="text/html" pageEncoding="utf-8"%><%@ page import="com.jspsmart.upload.*" %><html><head><title>smartupload組件上傳01</title></head><body> <%    SmartUpload smart = new SmartUpload() ;    smart.initialize(pageContext) ;    // 初始化上傳操作    smart.upload();        // 上傳準備    smart.save("upload") ;    // 文件保存    out.print("上傳成功");%> </body></html>

批量上傳:

html文件

<html><head><title>smartupload組件上傳02</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form action="smartupload_demo02.jsp" method="post" enctype="multipart/form-data">    圖片<input type="file" name="pic1"><br>    圖片<input type="file" name="pic2"><br>    圖片<input type="file" name="pic3"><br>    <input type="submit" value="上傳">    <input type="reset" value="重置"></form></body></html>

jsp代碼

smartupload_demo02.jsp
<%@ page contentType="text/html" pageEncoding="utf-8"%><%@ page import="com.jspsmart.upload.*"%><%@ page import="com.zhou.study.*"%><html><head><title>smartupload組件上傳02</title></head><body><%    SmartUpload smart = new SmartUpload() ;    smart.initialize(pageContext) ;    // 初始化上傳操作    smart.upload() ;            // 上傳準備    String name = smart.getRequest().getParameter("uname") ;    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // 取得客戶端的IP地址    for(int x=0;x<smart.getFiles().getCount();x++){        String ext = smart.getFiles().getFile(x).getFileExt() ;    // 擴展名稱        String fileName = its.getIPTimeRand() + "." + ext ;        smart.getFiles().getFile(x).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;    }    out.print("上傳成功");%></body></html>

注意:在TOMCAT_HOME/項目目錄下建立upload文件夾才能正常運行!

簡單上傳操作上傳后的文件名稱是原本的文件名稱。可通過工具類重命名。

另附上重命名工具類。

package com.zhou.study ;import java.text.SimpleDateFormat ;import java.util.Date ;import java.util.Random ;public class IPTimeStamp {    private SimpleDateFormat sdf = null ;    private String ip = null ;    public IPTimeStamp(){    }    public IPTimeStamp(String ip){        this.ip = ip ;    }    public String getIPTimeRand(){        StringBuffer buf = new StringBuffer() ;        if(this.ip != null){            String s[] = this.ip.split("http://.") ;            for(int i=0;i<s.length;i++){                buf.append(this.addZero(s[i],3)) ;            }        }        buf.append(this.getTimeStamp()) ;        Random r = new Random() ;        for(int i=0;i<3;i++){            buf.append(r.nextInt(10)) ;        }        return buf.toString() ;    }    public String getDate(){        this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;        return this.sdf.format(new Date()) ;    }    public String getTimeStamp(){        this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;        return this.sdf.format(new Date()) ;    }    private String addZero(String str,int len){        StringBuffer s = new StringBuffer() ;        s.append(str) ;        while(s.length() < len){            s.insert(0,"0") ;        }        return s.toString() ;    }    public static void main(String args[]){        System.out.println(new IPTimeStamp().getIPTimeRand()) ;    }}

附上使用方法:

<html><head><title>smartupload上傳文件重命名</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head><body><form action="smartupload_demo03.jsp" method="post" enctype="multipart/form-data">    姓名<input type="text" name="uname"><br>    照片<input type="file" name="pic"><br>    <input type="submit" value="上傳">    <input type="reset" value="重置"></form></body></html>

Jsp代碼:

smartupload_demo03.jsp
<%@ page contentType="text/html" pageEncoding="utf-8"%><%@ page import="com.jspsmart.upload.*" %><%@ page import="com.zhou.study.*"%><html><head><title>smartupload</title></head><body><%    SmartUpload smart = new SmartUpload() ;    smart.initialize(pageContext) ;    //初始化上傳操作    smart.upload() ;    // 上傳準備    String name = smart.getRequest().getParameter("uname") ;    String str = new String(name.getBytes("gbk"), "utf-8");    //傳值過程中出現亂碼,在此轉碼    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // 取得客戶端的IP地址     String ext = smart.getFiles().getFile(0).getFileExt() ;    // 擴展名稱    String fileName = its.getIPTimeRand() + "." + ext ;    smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;      out.print("上傳成功");%><h2>姓名:<%=str%></h2><img src="upload/<%=fileName%>"> </body></html>


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 肥乡县| 阿勒泰市| 扶沟县| 枣强县| 攀枝花市| 嘉善县| 定襄县| 明星| 宜丰县| 同江市| 常德市| 淳化县| 徐州市| 平邑县| 罗源县| 佳木斯市| 昌黎县| 岳普湖县| 广东省| 浙江省| 定兴县| 宜州市| 克东县| 民乐县| 余干县| 柳林县| 佛冈县| 简阳市| 共和县| 讷河市| 北京市| 肃北| 阿巴嘎旗| 克山县| 会东县| 乐昌市| 惠水县| 延庆县| 怀安县| 互助| 安顺市|