濮阳杆衣贸易有限公司

主頁 > 知識(shí)庫 > java使用smartupload組件實(shí)現(xiàn)文件上傳的方法

java使用smartupload組件實(shí)現(xiàn)文件上傳的方法

熱門標(biāo)簽:電銷機(jī)器人好賣么 商洛電銷 電銷機(jī)器人是有一些什么技術(shù) 四川保險(xiǎn)智能外呼系統(tǒng)商家 杭州語音電銷機(jī)器人軟件 北票市地圖標(biāo)注 高德地圖標(biāo)注樣式 杭州ai語音電銷機(jī)器人功能 地圖標(biāo)注線上教程

本文實(shí)例講述了java使用smartupload組件實(shí)現(xiàn)文件上傳的方法。分享給大家供大家參考。具體分析如下:

文件上傳幾乎是所有網(wǎng)站都具有的功能,用戶可以將文件上傳到服務(wù)器的指定文件夾中,也可以保存在數(shù)據(jù)庫中,這里主要說明smartupload組件上傳。

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

廢話不多說直接上代碼:

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

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

下面開始講解smartupload

smartupload是由www.jspsmart.com網(wǎng)站開發(fā)的一套上傳組件包,可以輕松的實(shí)現(xiàn)文件的上傳及下載功能,smartupload組件使用簡(jiǎn)單、可以輕松的實(shí)現(xiàn)上傳文件類型的限制、也可以輕易的取得上傳文件的名稱、后綴、大小等。

smartupload本身是一個(gè)系統(tǒng)提供的jar包(smartupload.jar),用戶直接將此包放到classpath下即可,也可以直接將此包拷貝到TOMCAT_HOME\lib目錄之中。

下面使用組件完成上傳

單一文件上傳:

復(fù)制代碼 代碼如下:
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

復(fù)制代碼 代碼如下:
%@ 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();        // 上傳準(zhǔn)備
    smart.save("upload") ;    // 文件保存
    out.print("上傳成功");
%>

/body>
/html>

批量上傳:

html文件


復(fù)制代碼 代碼如下:
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

復(fù)制代碼 代碼如下:
%@ 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() ;            // 上傳準(zhǔn)備
    String name = smart.getRequest().getParameter("uname") ;
    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // 取得客戶端的IP地址
    for(int x=0;xsmart.getFiles().getCount();x++){
        String ext = smart.getFiles().getFile(x).getFileExt() ;    // 擴(kuò)展名稱
        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/項(xiàng)目目錄下建立upload文件夾才能正常運(yùn)行!

簡(jiǎn)單上傳操作上傳后的文件名稱是原本的文件名稱??赏ㄟ^工具類重命名。

另附上重命名工具類。

復(fù)制代碼 代碼如下:
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("\\.") ;
            for(int i=0;is.length;i++){
                buf.append(this.addZero(s[i],3)) ;
            }
        }
        buf.append(this.getTimeStamp()) ;
        Random r = new Random() ;
        for(int i=0;i3;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()) ;
    }
}

附上使用方法:

復(fù)制代碼 代碼如下:
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

復(fù)制代碼 代碼如下:
%@ 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() ;    // 上傳準(zhǔn)備
    String name = smart.getRequest().getParameter("uname") ;
    String str = new String(name.getBytes("gbk"), "utf-8");    //傳值過程中出現(xiàn)亂碼,在此轉(zhuǎn)碼
    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // 取得客戶端的IP地址
     String ext = smart.getFiles().getFile(0).getFileExt() ;    // 擴(kuò)展名稱
    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>

希望本文所述對(duì)大家的jsp程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • JavaWeb實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
  • JAVA中使用FTPClient實(shí)現(xiàn)文件上傳下載實(shí)例代碼
  • java web圖片上傳和文件上傳實(shí)例
  • java實(shí)現(xiàn)FTP文件上傳與文件下載
  • java中struts2實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
  • java實(shí)現(xiàn)文件上傳下載和圖片壓縮代碼示例
  • java基于servlet實(shí)現(xiàn)文件上傳功能解析
  • JavaEE實(shí)現(xiàn)前后臺(tái)交互的文件上傳與下載
  • java文件上傳下載功能實(shí)現(xiàn)代碼
  • java組件SmartUpload和FileUpload實(shí)現(xiàn)文件上傳功能

標(biāo)簽:宿州 青島 紅河 江西 丹東 貴州 西藏 云浮

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《java使用smartupload組件實(shí)現(xiàn)文件上傳的方法》,本文關(guān)鍵詞  java,使用,smartupload,組件,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《java使用smartupload組件實(shí)現(xiàn)文件上傳的方法》相關(guān)的同類信息!
  • 本頁收集關(guān)于java使用smartupload組件實(shí)現(xiàn)文件上傳的方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    保靖县| 林口县| 澜沧| 鸡泽县| 南溪县| 怀远县| 波密县| 武穴市| 上犹县| 鄱阳县| 弥勒县| 灵丘县| 华容县| 水城县| 吉木萨尔县| 札达县| 抚松县| 湖北省| 阆中市| 乌海市| 克山县| 周至县| 巧家县| 鄂尔多斯市| 溧阳市| 通化县| 海晏县| 昂仁县| 黑水县| 宜宾县| 邹平县| 五大连池市| 通州市| 泾阳县| 海伦市| 兴业县| 康平县| 田阳县| 墨脱县| 西乡县| 清镇市|