struts2 文件下载

package com.cioside.web;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.cioside.entity.Attachment;
import com.cioside.service.UploadManager;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Namespace("/service")
@Result(type = "stream", params = { "contentType",
  "application/octet-stream;charset=ISO8859-1", "inputName",
  "downloadFile", "contentDisposition",
  "attachment;filename=${downloadChineseFileName}", "bufferSize", "4096" })
public class DownloadAction extends ActionSupport {

 private static final long serialVersionUID = -7815222637330155732L;

 @Autowired
 private UploadManager uploadManager;
 private String fileName;
 private Long workId;
 private Long id;
 private String msg;

 public InputStream getDownloadFile() {
  InputStream in = null;
  try {

   Attachment attachment = new Attachment();
   if (id != null) {
    attachment = uploadManager.getAttachment(id);
   }
   HttpServletResponse response = Struts2Utils.getResponse();
   response.setContentType("application/x-download");
   response.setHeader("Content-Disposition", "attachment; fileName="
     + java.net.URLEncoder.encode(fileName, "ISO8859-1"));
   in = new FileInputStream(attachment.getLocation());

   if (in == null) {
    System.out
      .println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");
   }
   response.reset();
  } catch (Exception e) {
   msg = "文件不存在!";
  }

  return in;
 }

 // 如果下载文件名为中文,进行字符编码转换
 public String getDownloadChineseFileName() {
  String downloadChineseFileName = fileName;

  try {
   downloadChineseFileName = new String(downloadChineseFileName
     .getBytes(), "ISO8859-1");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }

  return downloadChineseFileName;
 }

 @Override
 public String execute() throws Exception {

  return "success";
 }

 public String getFileName() {

  return fileName;
 }

 public void setFileName(String fileName) {

  this.fileName = fileName;
 }

 public Long getWorkId() {
  return workId;
 }

 public void setWorkId(Long workId) {
  this.workId = workId;
 }

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值