Struts2文件上传和下载

上传

index.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript"> $(function() { $("#btn_upd").click( function() { // alert($("#file").val().substring($("#file").val().lastIndexOf("\\")+1) ); $("#fname").val( $("#file").val().substring( $("#file").val().lastIndexOf("\\") + 1)); //提交 $("#upld").attr("action", "Upload.action").submit(); }); }); </script>
</head>
<body>
红色的地方需要注意
    <p>struts2上传文件</p>
    <form id="upld" method="post" enctype="multipart/form-data">
        <input name="fname" id="fname" type="hidden"> 
这个type类型表示这个文件的File类型的
         文件资料:<input type="file" id="file" name="upfile"><br> <input type="button" id="btn_upd" value="上传">
    </form>
    ${msg }
</body>
</html>

upload.jsp

<body>
   <s:iterator var="fileName" value="fileNames" status="status">
        <a href="downFile.action?fno=<s:property value="#status.count" />">
            <s:property value="#fileName" /> </a>
        <br>
    </s:iterator>
  </body>

对应的Action处理类


package com.act;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport{
    private String fname;
    private File upfile;
    private String msg;
    @Override
    @Action(value = "Upload", results = { @Result(location = "upload.jsp") })
    public String execute() throws Exception {
        // 标准io流
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(upfile));
        BufferedOutputStream bos = new BufferedOutputStream(
                //开辟了一个名为c:\\fname的空间来存文件
                new FileOutputStream("C:\\" + fname));
        byte[] buf = new byte[1024 * 10];
        while (bin.read(buf) != -1) {
            bos.write(buf);
        }
        bos.flush();
        bos.close();
        bin.close();
        msg = fname + "上传成功!";
        return SUCCESS;}
    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public File getUpfile() {
        return upfile;
    }
    public void setUpfile(File upfile) {
        this.upfile = upfile;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }


}

上传

文件下载也是前面的index.jsp,然后来个upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript"> $(function() { $("#btn_upd").click( function() { // alert($("#file").val().substring($("#file").val().lastIndexOf("\\")+1) ); $("#fname").val( $("#file").val().substring( $("#file").val().lastIndexOf("\\") + 1)); //提交 $("#upld").attr("action", "Upload.action").submit(); }); }); </script>
</head>
<body>
    <p>struts2上传文件</p>
    <form id="upld" method="post" enctype="multipart/form-data">
        <input name="fname" id="fname" type="hidden"> 
         文件资料:<input type="file" id="file" name="upfile"><br> <input type="button" id="btn_upd" value="上传">
    </form>
    ${msg }
</body>
</html>

对应的action处理


package com.act;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("down")
public class DownAction extends ActionSupport {
    private String[] fileNames;
    private Integer fno;
    private String fname;
    private String tmp;
    private final static String downPath = "F:\\test";
    private String mimeType;

    @Action(value = "toDown", results = { @Result(location = "down.jsp") })
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        File file = new File(downPath);
        //默认放到值栈里面
        fileNames = file.list();
        return SUCCESS;
    }
    public String downFile() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        // 文件编号 -->文件名
        fileNames = new File(downPath).list();
        tmp = fileNames[fno - 1];
        fname = tmp;
        // fname = java.net.URLEncoder.encode(fname, "UTF-8");

        try {
            String path = downPath + "//"
                    + new String(fname.getBytes("ISO8859-1"), "utf-8");
            System.out.println(path);
            mimeType = ServletActionContext.getServletContext().getMimeType(
                    path)
                    + ";charset=UTF-8";
            System.out.println("mimeType:" + mimeType);
            String agent = request.getHeader("USER-AGENT");
            System.out.println(agent);
            if (null != agent) {
                if (-1 != agent.indexOf("Firefox")) {// Firefox
                    mimeType = mimeType.replace("UTF-8", "ISO8859-1");
                    fname = new String(fname.getBytes("GB2312"), "ISO-8859-1");
                } else {// IE7+ Chrome
                    System.out.println("IE,Chrome");
                    // fname = new String(fname.getBytes("ISO8859-1"), "utf-8");
                    System.out.println("--------------->" + fname);
                    fname = java.net.URLEncoder.encode(fname, "UTF-8");
                    System.out.println("--------------->" + fname);
                }
            }
            System.out.println(fname);
        } catch (Exception e) {
            System.out.println("下载文件信息出错。");
        }

        return SUCCESS;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    // ///真正操作下载的逻辑
    public InputStream getDownFile() throws FileNotFoundException {
        return new FileInputStream(new File(downPath, tmp));
    }

    public Integer getFno() {
        return fno;
    }

    public void setFno(Integer fno) {
        this.fno = fno;
    }

    public String[] getFileNames() {
        return fileNames;
    }

    public void setFileNames(String[] fileNames) {
        this.fileNames = fileNames;
    }

}

你可能感兴趣的:(下载,上传,struts2.0)