文件下载1
package com.hss.esale.action.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.hss.esale.action.common.Constants;
/**
* 模块名:资源文件下载
* @author 黄侨红
*
*/
public class DownLoadFileController extends AbstractController {
private static final Log log = LogFactory.getLog(DownLoadFileController.class);
private static final String CONTENT_TYPE = "application/x-msdownload";
private String uploadFilePath; //文件存储硬盘地址
public void setUploadFilePath(String uploadFilePath) {
this.uploadFilePath = uploadFilePath;
}
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setCharacterEncoding(Constants.UTF_8);
/**取文件格式名*/
String fileName = URLDecoder.decode(request.getParameter("filePath"), "UTF-8");
if(fileName.equals("pointsCardApplication.doc")){
fileName=URLDecoder.decode("积分卡申请表.doc", "UTF-8");;
}
/**文件存放完整路径*/
String fullFilePath = uploadFilePath + fileName;
log.info(fullFilePath);
/**读取文件*/
File file = new File(fullFilePath);
/**如果文件存在*/
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), Constants.UTF_8);
response.reset();
response.setContentType(CONTENT_TYPE);
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/**如果文件长度大于0*/
if (fileLength != 0) {
/**创建输入流*/
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
/**创建输出流*/
ServletOutputStream servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}
return null;
}
}
文件下载2
@RequestMapping("/download.htm")
public ModelAndView download(HttpServletRequest request,
HttpServletResponse response) throws Exception {
File file = new File("D:\\test\\abc.ppt");
response.setContentType("application/vnd.ms-powerpoint");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
return null;
}