struts 檔案下載

來源:互聯網
上載者:User

標籤:

=============================struts 檔案下載  ==================================

步驟一: JSP頁面
<a href="download.action?fileName=IMG_0443.JPG">點擊此處下載圖片</a>

步驟二: Action頁面

package org.zm.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport{
//讀取下載檔案的目錄
private String inputPath;
//下載檔案的檔案名稱
private String fileName;
//讀取下載檔案的輸入資料流
private InputStream inputStream;

//下載檔案的類型
private String conetntType;

//建立InputStream輸入資料流
public InputStream getInputStream() throws FileNotFoundException{
String path=ServletActionContext.getServletContext().
getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"\\"+
fileName));
}

@Override
public String execute() {
return SUCCESS;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getConetntType() {
return conetntType;
}


public String getInputPath() {
return inputPath;
}


public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public void setConetntType(String conetntType) {
this.conetntType = conetntType;
}
}

 

步驟三: Struts.xml檔案
<action name="download" class="org.zm.action.DownLoadAction">
<param name="inputPath">/upload</param>
<result name="success" type="stream">
<param name="contentType">image/pjpeg</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>


提示: Stream結果類型
contentType: 設定發送到瀏覽器的MIME類型
contentLength: 檔案大小
contentDisposition: 設定響應的HTTP頭資訊的Content-Disposition參數的值
inputName: 指定Action提供的inputStream類型的屬性名稱
bufferSize:設定讀取和下載檔案時緩衝區的大小

struts.xml檔案和Action 這兩處位置的變數名稱一定要正確。

struts 檔案下載

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.