Struts1文件上传下载

首先建立web项目,引入struts,这些我就不再多说。

一、现在我直接来写JSP页面。

register.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'register.jsp' starting page</title>
  </head>
 
  <body>
    <h1>注册用户</h1>
    <form enctype="multipart/form-data" action="/strutsFileUpandDown/register.do" method="post">
    名字:<input type="text" name="name"/><br/>
    头像:<input type="file" name="myphoto"/><br/>
    <input type="submit" value="注册用户"/>
    </form>
  </body>
</html>

二、写UserForm表单和RegisterAction

UserForm:

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
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package com.lpq.struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

/**
 * MyEclipse Struts
 * Creation date: 01-21-2013
 *
 * XDoclet definition:
 * @struts.form name="userForm"
 */

public class UserForm extends ActionForm {
    private String name;
    private FormFile myphoto;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public FormFile getMyphoto() {
        return myphoto;
    }
    public void setMyphoto(FormFile myphoto) {
        this.myphoto = myphoto;
    }
}

三、配置相关的跳转关系。

四、文件上传业务逻辑处理。

文件上传细节问题:1.中文名字的文件    2.存在文件会覆盖

1.使用过滤器统一设置文件的编码。

过滤器代码:

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
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package com.lpq.struts.action;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lpq.domain.Users;
import com.lpq.service.UserService;

/**
 * MyEclipse Struts
 * Creation date: 01-22-2013
 *
 * XDoclet definition:
 * @struts.action
 */

public class DownloadFileAction extends Action {
    /*
     * Generated Methods
     */


    /**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        //获得用户名
        String username = request.getParameter("user");
        //获取User对象
        UserService userSevice = new UserService();
        Users user = userSevice.getUser(username);
       
        response.setContentType("text/html;charset=UTF-8");
        //如果文件名有中文,需要进行url编码
        String filterFilename = "";
        try {
            filterFilename = URLEncoder.encode(user.getPhotos2(), "UTF-8");
            //filterFilename = new String(user.getPhotos2().getBytes("gb2312"),"ISO8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        //设置一个头告诉浏览器有文件要下载
        response.setHeader("Content-Disposition", "attachment;filename="+filterFilename);
       
        String filePath = this.getServlet().getServletContext().getRealPath("/file");
        String fileAllPath = filePath+"\"+user.getPhotos();
        FileInputStream fis = null;
        OutputStream os = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            fis = new FileInputStream(fileAllPath);
            os = response.getOutputStream();
            while((len=fis.read(buffer))>0){
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                os.flush();  
                os.close();  
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
}

2.每次上传的文件我们使用UUID生成随机的不重复的字符串。封装成如下工具类。

1
2
3
4
5
6
7
8
9
10
11
package com.lpq.utils;

import java.util.UUID;

public class MyTools {
    public static String getNewFileName(String fileName){
        int beginIndex = fileName.lastIndexOf(".");
        String newFilename = UUID.randomUUID().toString()+fileName.substring(beginIndex);
        return newFilename;
    }
}

五、文件下载业务逻辑处理

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
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package com.lpq.struts.action;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lpq.domain.Users;
import com.lpq.service.UserService;

/**
 * MyEclipse Struts
 * Creation date: 01-22-2013
 *
 * XDoclet definition:
 * @struts.action
 */

public class DownloadFileAction extends Action {
    /*
     * Generated Methods
     */


    /**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        //获得用户名
        String username = request.getParameter("user");
        //获取User对象
        UserService userSevice = new UserService();
        Users user = userSevice.getUser(username);
       
        response.setContentType("text/html;charset=UTF-8");
        //如果文件名有中文,需要进行url编码
        String filterFilename = "";
        try {
            filterFilename = URLEncoder.encode(user.getPhotos2(), "UTF-8");
            //filterFilename = new String(user.getPhotos2().getBytes("gb2312"),"ISO8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        //设置一个头告诉浏览器有文件要下载
        response.setHeader("Content-Disposition", "attachment;filename="+filterFilename);
       
        String filePath = this.getServlet().getServletContext().getRealPath("/file");
        String fileAllPath = filePath+"\"+user.getPhotos();
        FileInputStream fis = null;
        OutputStream os = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            fis = new FileInputStream(fileAllPath);
            os = response.getOutputStream();
            while((len=fis.read(buffer))>0){
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                os.flush();  
                os.close();  
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
}

 

除非注明,Coder文章均为原创,转载请以链接形式标明本文地址

本文地址:http://www.alonemonkey.com/fileupanddown.html

本文链接:http://www.alonemonkey.com/struts1%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd.html