且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Struts文件上传,下载,重传,预览

更新时间:2022-09-13 13:38:43

    今日群里一兄弟问我能否给一份struts文件上传下载的例子,因为自己项目比较紧所以想在网上找

些源码给他,但是纵观全网,写的都不是太全,这让新手使用都不是太方便,利用周天花了30分钟写了

个。发布出来,发布出来大家共同学习!其中包括数据库的设计路径存储重现上传删除服务器源

图片预览,等!


知识你我共同分享!

首先明白文件上传下载的原理。

、利用输入流个输出流InputStream OutputStream

②、我们的Struts自带的FileUtiles.copyFile上传组件的!

本文采用的事第二种!另为了方便读者可以直接的使用本源码,采取的事多文件上传。一劳永逸!另由于时间关系,采用存储方式是JDBCMysql


第一步:我们需要相关的开发架包:

Struts文件上传,下载,重传,预览

如果这几个的意思您不懂可以直接百度。也可以给我留言!


第二步:建立我的数据库表结构

Struts文件上传,下载,重传,预览


第三步:编写我们的DBUtil


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package org.usc.util;
import java.sql.*;
public class DBUtil {
    public static Connection conn = null;
    public static Connection getConn() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/oracle""root""root");
        catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void close() {
        if (conn != null) {
            try {
                conn.close();
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        getConn();
        System.out.println(getConn());
    }
}

第四步:编写实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package org.usc.entity;
/**
 * 文件类,需要的时候,可以和数据库进行关联
 *
 */
public class UploadFiles
{
    private String uploadFileName;//上传的文件名称
    private String uploadContentType;//类型
    private String uploadRealName;//服务器保存的文件真实名称,UUID
    private String txt;
    private String path;
    //如果使用数据库的话,建议这三个字段都进行保存
    public String getUploadFileName()
    {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName)
    {
        this.uploadFileName = uploadFileName;
    }
    public String getUploadContentType()
    {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentType)
    {
        this.uploadContentType = uploadContentType;
    }
    public String getUploadRealName()
    {
        return uploadRealName;
    }
    public void setUploadRealName(String uploadRealName)
    {
        this.uploadRealName = uploadRealName;
    }
    public String getTxt() {
        return txt;
    }
    public void setTxt(String txt) {
        this.txt = txt;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
                                                                                                                                                                        
                                                                                                                                                                        
}

第五步:编写相关Dao方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.usc.dao;
import java.sql.*;
import org.usc.entity.UploadFiles;
import org.usc.util.DBUtil;
public class Dao {
                                                                                                                                                                    
    public boolean add(UploadFiles uploadFiles ){
        boolean result=false;
        Connection conn=DBUtil.getConn();
        try {
            PreparedStatement ps=conn.prepareStatement("insert into UploadFiles(uploadFileName,uploadRealName,uploadContentType,txt,path)values(?,?,?,?,?)");
            ps.setString(1, uploadFiles.getUploadFileName());
            ps.setString(2, uploadFiles.getUploadRealName());
            ps.setString(3, uploadFiles.getUploadContentType());
            ps.setString(4, uploadFiles.getTxt());
            ps.setString(5, uploadFiles.getPath());
            ps.execute();
            result=true;
        catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.close();
        }
        return result;
    }
                                                                                                                                                                    
    // 根据ID的编号查询
        public UploadFiles querykById(int id) {
            Connection conn = DBUtil.getConn();
            UploadFiles uploadFiles = new UploadFiles();
            try {
                PreparedStatement ps = conn
                        .prepareStatement("select*from UploadFiles where id = ?");
                ps.setInt(1, id);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    uploadFiles.setPath(rs.getString("path"));
                    uploadFiles.setTxt(rs.getString("txt"));
                    uploadFiles.setUploadFileName(rs.getString("uploadFileName"));
                    uploadFiles.setUploadRealName(rs.getString("uploadRealName"));
                    uploadFiles.setUploadContentType(rs.getString("uploadContentType"));
                                                                                                                                                                                    
                }
            catch (SQLException e) {
                e.printStackTrace();
            }
            return uploadFiles;
        }
}

第六步:编写上传Action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package org.usc.action;
import java.io.File;
import java.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.usc.dao.Dao;
import org.usc.entity.UploadFiles;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private File[] upload;// 实际上传文件
    private String[] uploadContentType; // 文件的内容类型
    private String[] uploadFileName; // 上传文件名
    // 注意FileName和ContentType 必须这样写!以你的<input type="file" name="upload">
    private List<UploadFiles> uploadFiles = new ArrayList<UploadFiles>();// 上传文件集合
    private String message;
    public static String FILE_ROOT = "";
    public static String UPLOAD_PATH = "/upload"// 上传文件路径
    public String execute() throws Exception {
        try {
            String path = ServletActionContext.getServletContext().getRealPath(
                    FILE_ROOT);
            String path2 = UPLOAD_PATH + "/shangchuan/";
            String targetDirectory = path + path2;
            File file = new File(targetDirectory);// 获取文件流路径
            if (!file.exists()) {
                file.mkdirs();
            }
            for (int i = 0; i < upload.length; i++) {
                String fileName = uploadFileName[i];// 上传的文件名
                String type = uploadContentType[i];// 文件类型
                String realName = UUID.randomUUID().toString()
                        + getExt(fileName);// 保存的文件名称,使用UUID+后缀进行保存
                File target = new File(targetDirectory, realName);
                FileUtils.copyFile(upload[i], target);// 上传至服务器的目录,一般都这样操作,
                /*
                 * UploadFiles uf = new UploadFiles();// 创建文件
                 * uf.setUploadContentType(type);
                 * uf.setUploadFileName(fileName);//上传的文件名称
                 * uf.setUploadRealName(realName);//保存数据库的文件名称 采用加密形式
                 * uploadFiles.add(uf);// 添加到需要下载文件的List集合中
                 */// uploadRealName[i]=UUID.randomUUID().toString();
                    // System.out.println("uploadRealName:"+uploadRealName[i]);
                /*
                 * for(File file:upload){
                 * System.out.println("filename:"+file.getName()); }
                 */
                System.out.println("filename真实的名字:" + fileName);
                System.out.println("保存数据库中的加密名字" + realName);
                System.out.println("Ext-后缀名:" + getExt(fileName));
                System.out.println("Type-类型:" + type);
                System.out.println("上传路径:" + path2 + realName);
                System.out.println("----------------------------");
                // 下面我们将相关的信息保存到数据库中去
                UploadFiles uploadFiles = new UploadFiles();
                uploadFiles.setPath(path2 + realName);
                uploadFiles.setTxt(getExt(fileName));
                uploadFiles.setUploadContentType(type);
                uploadFiles.setUploadFileName(fileName);
                uploadFiles.setUploadRealName(realName);
                Dao dao = new Dao();
                dao.add(uploadFiles);
            }
            // 通过dao方法根据ID值查出所对应对象的属性,在页面显示出来
            Dao dao = new Dao();
            UploadFiles ed = dao.querykById(109);// 这是我测试用的id值 您的Id初始值应该为1
            uploadFiles.add(ed);
            System.out
                    .println(uploadFiles.get(0).getUploadFileName() + ">>>>>");
        catch (Exception e) {
            e.printStackTrace();
            addActionError(e.getMessage());
        }
        return SUCCESS;
    }
    // 本方法是截取后缀名的 不会的话百度搜索IndexOf方法
    public static String getExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
    //下面是get set方法
    public File[] getUpload() {
        return upload;
    }
    public void setUpload(File[] upload) {
        this.upload = upload;
    }
    public String[] getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public String[] getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public List<UploadFiles> getUploadFiles() {
        return uploadFiles;
    }
    public void setUploadFiles(List<UploadFiles> uploadFiles) {
        this.uploadFiles = uploadFiles;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

第七步:编写下载Action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.usc.action;
import java.io.*;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
public class DownloadAction extends ActionSupport {
    private static final long serialVersionUID = 6329383258366253255L;
    private String fileName;
    private String fileRealName;
    public String path;
    public static String FILE_ROOT = "";
    public void setFileName() {
        // 得到请求下载的文件名
        String fname = ServletActionContext.getRequest().getParameter("name");
        String frealname = ServletActionContext.getRequest().getParameter(
                "realname");
        try {
            /*
             * 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。
             * 这里使用request.setCharacterEncoding解码无效.
             * 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件
             */
            fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
            frealname = new String(frealname.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.fileName = fname;
        this.fileRealName = frealname;
        // System.out.println(fileName);
        // System.out.println(fileRealName);
    }
    /*
     * @getFileName 此方法对应的是struts.xml文件中的: <param
     * name="contentDisposition">attachment;filename="${fileName}"</param>
     * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码
     * 否则中文名文件将出现乱码,或无法下载的情况
     */
    public String getFileName() throws UnsupportedEncodingException {
        fileRealName = new String(fileRealName.getBytes(), "ISO-8859-1");
        return fileRealName;
    }
    /*
     * @getDownloadFile 此方法对应的是struts.xml文件中的: <param
     * name="inputName">downloadFile</param> 返回下载文件的流,可以参看struts2的源码
     */
    public InputStream getDownloadFile() {
        this.setFileName();
        String uploadPath = ServletActionContext.getRequest().getParameter(
                "path");
        String path3 = ServletActionContext.getServletContext().getRealPath(
                FILE_ROOT);
        String path = uploadPath;
        String path1 = (path3 + path);
        File file = new File(path1);
        InputStream file1 = null;
        try {
            file1 = new FileInputStream(file);
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file1;
    }
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
}

第八步:配置struts.xmlweb.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.i18n.encoding" value="utf8" />
    <constant name="struts.multipart.maxSize" value="10485760"/>
    <package name="file" namespace="/" extends="struts-default">
        <action name="showUpload">
            <result>/upload.jsp</result>
        </action>
        <action name="upload" class="org.usc.action.UploadAction">
            <result name="input">/upload.jsp</result>
            <result name="success">/download.jsp</result>
                                                                                                                                                            
                    <interceptor-ref name="fileUpload">
<!--大家可以设置成自己的配置,想文件类型和大小等限制         -->
                <param name="maximumSize">2097152</param>
<!--             <param name="allowedTypes">image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg</param>-->
<!--             -->
<!--                 容许文件类型为doc,ppt,xls,pdf,txt,java-->
<!--             -->
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
                                                                                                                                                            
        </action>
        <action name="download" class="org.usc.action.DownloadAction">
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;filename="${fileName}"</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
</struts>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <welcome-file-list>
        <welcome-file>upload.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


第九步:编写上传jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
    <head>
        <title>upload</title>
    </head>
    <body>
<script type="text/javascript">
<!--addMore函数可以提供上传多个文件上传-->
function addMore()
{
    var td = document.getElementById("more");
    var br = document.createElement("br");
    var input = document.createElement("input");
    var button = document.createElement("input");
    input.type = "file";
    input.name = "upload";
    button.type = "button";
    button.value = "   删除    ";
    button.onclick = function()
    {
        td.removeChild(this);
    }
    td.appendChild(br);
    td.appendChild(input);
    td.appendChild(button);
}
</script>
        <!--<h3><font color="red">上传文件类型后缀为doc,ppt,xls,pdf,txt,java,每个文件大小不能大于50M</font></h3>-->
        <table align="center" width="50%">
            <tr>
                <td>
                    <s:fielderror cssStyle="color:red" />
                </td>
            </tr>
        </table>
                                                                                                                                                  
        <s:form action="upload.action" theme="simple" method="post"
            enctype="multipart/form-data">
            <table align="center" width="50%" border="1">
                <tr>
                    <td>
                        上传文件
                    </td>
                    <td id="more" >
                        <s:file name="upload"></s:file>
                        <input type="button" value="上传更多..."                     </td>
                </tr>
                <tr>
                    <td>
                        <s:submit value=" 确认 "></s:submit>
                    </td>
                    <td>
                        <s:reset value=" 重置 "></s:reset>
                    </td>
                </tr>
            </table>
        </s:form>
    </body>
</html>


第十步:编写下载jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
    <head>
        <title>download</title>
                                                                                                                                              
    </head>
    <body>
                                                                                                                                          
        <table align="center" width="50%" border="1">
            <tr>
                <td align="center">
                    文件下载
                </td>
            </tr>
            <c:forEach  items="${uploadFiles}" var="uploadFiles">
                <tr>
                    <td>
                        <a href="download.action?name=${uploadFiles.uploadRealName }&realname=${uploadFiles.uploadFileName }&path=${uploadFiles.path}">${uploadFiles.uploadFileName }</a>
                    </td>
                    <td><img src='/update${uploadFiles.path}'></td><!--这个格式是工程名/存储路径   由于我的工程名字是update名字起得不好,所以大家可以自己修改 -->
                </tr>
            </c:forEach>
        </table>
    </body>
</html>


访问路径:http://127.0.0.1:8080/update/upload.jsp

第十一步:测试页面

Struts文件上传,下载,重传,预览






第十二步:下载页面

Struts文件上传,下载,重传,预览



本项目兼容SSH框架的项目稍加修改,即可使用!如有问题请到QQ群:160243674去找我!


项目结构

Struts文件上传,下载,重传,预览


源码下载地址:

http://down.51cto.com/data/998161











本文转自 小夜的传说 51CTO博客,原文链接:http://blog.51cto.com/1936625305/1319656,如需转载请自行联系原作者