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