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>

대응하는 액션 처리

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

}

좋은 웹페이지 즐겨찾기