当前位置: 移动技术网 > IT编程>开发语言>Java > java使用smartupload组件实现文件上传的方法

java使用smartupload组件实现文件上传的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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("\\.")[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("\\.")[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("\\.") ;
            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>

希望本文所述对大家的jsp程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网