package com.smbea.demo.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 文件下载
* @author hapday
* @date 2017年1月23日 @time上午10:58:04
*/
@Controller
@RequestMapping( value = "admin/file" )
public class FileDownloadController {
protected static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadController.class);
@RequestMapping(value = "fileDownloadTest", method = { RequestMethod.GET, RequestMethod.POST })
public void fileDownloadTest(HttpServletRequest request, HttpServletResponse response) {
String fileName = "test.pdf";
try {
fileName = URLEncoder.encode("软件秘笈设计模式那点事.pdf", "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// System.out.println(request.getServletContext().getMimeType(fileName));
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);// 指定下载的文件名
response.setContentType("application/octet-stream");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
URL url = null; // URL 地址
try {
url = new URL("http://www.smbea.com/pdf/软件秘笈设计模式那点事.pdf");
} catch (MalformedURLException e) {
LOGGER.error("无效的 PDF 文件。", e);
e.printStackTrace();
}
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // 打开 HTTP 连接
httpURLConnection.setDoOutput(true);
int responseCode = httpURLConnection.getResponseCode();
System.out.println("responseCode = " + responseCode);
if(500 == responseCode) {
System.out.println("HttpURLConnection 内部错误!");
return;
}
if(404 == responseCode) {
System.out.println("文件未找到!");
return;
}
if(200 != responseCode) {
return ;
}
InputStream inputStream = httpURLConnection.getInputStream(); // 获取 HTTP 连接中的输入流
OutputStream outputStream = response.getOutputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
int len = 2048;
byte[] b = new byte[len];
while(-1 != (len = bufferedInputStream.read(b))) {
bufferedOutputStream.write(b, 0, len);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
outputStream.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
LOGGER.error("文件下载 - 失败!", e);
e.printStackTrace();
}
}
}