java uses the smartupload component to upload files

  • 2021-06-29 11:46:21
  • OfStack

This article provides an example of how java uses the smartupload component to upload files.Share it for your reference.Specific analysis is as follows:

File upload is a feature that almost all Web sites have. Users can upload files to a specified folder on the server or save them in a database. This is mainly about smartupload component upload.

Before explaining smartupload upload, let's first look at how uploading works without components.

Say nothing but code directly:

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()) {                // 依次取出每1个上传项
            FileItem item = iter.next();         // 取出每1个上传的文件
            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) {     // 取得1个参数
        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) { // 取得1组上传内容
        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()) {            // 循环取出每1个上传文件
                FileItem item = this.files.get(iter.next()); // 依次取出每1个文件
                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;                            // 接收每1个字节
                    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;                            // 返回生成后的文件名称
    }
}

The above code will complete the component-free upload.

Let's start with smartupload

smartupload is a set of upload component package developed by www.jspsmart.com website, which can easily upload and download files. smartupload components are simple to use, can easily realize the limitation of upload file type, and can easily get the name, suffix, size of uploaded files, etc.

smartupload itself is a system-provided jar package (smartupload.jar), which users can either place directly under classpath or copy directly to TOMCAT_In the HOMElib directory.

Next complete the upload using components

Single 1 file upload:

<html>
<head><title>smartupload Component Upload </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">
    picture <input type="file" name="pic">
    <input type="submit" value=" upload ">
</form>
</body>
</html>

jsp code:

smartupload_demo01.jsp

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<html>
<head><title>smartupload Component Upload 01</title></head> <body>
 <%
    SmartUpload smart = new SmartUpload() ;
    smart.initialize(pageContext) ;    // Initialize upload operation
    smart.upload();        // Preparing for upload
    smart.save("upload") ;    // file save
    out.print(" Upload Successful ");
%> </body>
</html>

Bulk upload:

html file


<html>
<head><title>smartupload Component Upload 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">
    picture <input type="file" name="pic1"><br>
    picture <input type="file" name="pic2"><br>
    picture <input type="file" name="pic3"><br>
    <input type="submit" value=" upload ">
    <input type="reset" value=" Reset ">
</form>
</body>
</html>

jsp Code

smartupload_demo02.jsp

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*"%>
<%@ page import="com.zhou.study.*"%>
<html>
<head><title>smartupload Component Upload 02</title></head>
<body>
<%
    SmartUpload smart = new SmartUpload() ;
    smart.initialize(pageContext) ;    // Initialize upload operation
    smart.upload() ;            // Preparing for upload
    String name = smart.getRequest().getParameter("uname") ;
    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // Get Client's IP address
    for(int x=0;x<smart.getFiles().getCount();x++){
        String ext = smart.getFiles().getFile(x).getFileExt() ;    // Extension Name
        String fileName = its.getIPTimeRand() + "." + ext ;
        smart.getFiles().getFile(x).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;
    }
    out.print(" Upload Successful ");
%>
</body>
</html>

Note: In TOMCAT_Create the upload folder under the HOME/project directory to work properly!

The file name uploaded from a simple upload operation is the original file name.You can rename it through a tool class.

Renaming tool classes are also attached.

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()) ;
    }
}

Attached methods of use:

<html>
<head><title>smartupload Upload File Rename </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">
    Full name <input type="text" name="uname"><br>
    Photo <input type="file" name="pic"><br>
    <input type="submit" value=" upload ">
    <input type="reset" value=" Reset ">
</form>
</body>
</html>

Jsp code:

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) ;    // Initialize upload operation
    smart.upload() ;    // Preparing for upload
    String name = smart.getRequest().getParameter("uname") ;
    String str = new String(name.getBytes("gbk"), "utf-8");    // Random code occurs during value transfer and is transcoded here
    IPTimeStamp its = new IPTimeStamp("192.168.1.1") ;    // Get Client's IP address
     String ext = smart.getFiles().getFile(0).getFileExt() ;    // Extension Name
    String fileName = its.getIPTimeRand() + "." + ext ;
    smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ; 
    out.print(" Upload Successful ");
%> <h2> Full name: <%=str%></h2>
<img src="upload/<%=fileName%>">
</body>
</html>

I hope that the description in this paper will be helpful to everyone's jsp program design.


Related articles: