当前位置: 代码迷 >> Java相关 >> java基础篇-文件上传(组件)
  详细解决方案

java基础篇-文件上传(组件)

热度:516   发布时间:2016-04-22 20:46:30.0
java基础篇---文件上传(组件)

文件上传几乎是所有网站都具有的功能,用户可以将文件上传到服务器的指定文件夹中,也可以保存在数据库中,本篇主要说明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>

 

1楼疯子乙
废话不多说直接上代码
  相关解决方案