언어/Java

[java]파일 다운로드 1

antoroong 2025. 2. 7. 01:37

프로젝트 이름 : N

IDE : 이클립스

DB : mysql

SQL : ibatis

OS : centos 7

server : tomcat 6

jdk : 1.6

프레임워크 : 전자정부프레임워크 3.8

 

준비물

 Action.class (비즈니스 로직)

xml (struts)

 

 

1. xml에서 다운로드 url 설정하기

<?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>

    
    <package name="file" namespace="/IFile" extends="struts-default, tiles-default">
		
				<action name="fileDown" class="test.file.action.FileAction" method="fileDown">
				<result type="stream">
					<param name="contentType">application/octet-stream</param>
		      <param name="contentLength">${contentLength}</param>
	        <param name="contentDisposition">${contentDisposition}</param>
	        <param name="bufferSize">4096</param>
				</result>
			</action>
    </package>

</struts>

 

 

2. class파일로 비즈니스 로직 코딩

public class FileAction extends ActionSupport implements Preparable, ModelDriven<FileBean> {


	
	// 파일 다운로드 변수 1번의 XML에 param name으로 지정된 변수이름
	private InputStream inputStream;
	private int contentLength;
	private String contentDisposition;
	private String downFile;

  // 파일다운로드
	public String fileDown(){

		 //원본 파일이름과 경로 출력하기
      String file_real_path = "/home/test/file"
			String file_name = "file_name";	//원본 file_name
			String file_path = file_real_path + "/" + file_name;

				try{
					 File dFile = new File(file_path)

					 contentLength = (int)dFile.length();
					 contentDisposition = "attachment;filename=\"" +URLEncoder.encode(file_name,"utf-8").replace("+", "%20") + "\";";
					 inputStream = new FileInputStream(dFile);
				
				}catch(Exception e){
					e.printStackTrace();
					System.out.println("e:"+e);
			}
			
			return SUCCESS;
		}
		

 public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

}

 

프로젝트 이름 : N

IDE : 이클립스

DB : mysql

SQL : ibatis

OS : centos 7

server : tomcat 6

jdk : 1.6

프레임워크 : 전자정부프레임워크 3.8