import org.apache.commons.io.IOUtils;
/**
* 文件下载
* @param request
* @param response
*/
@RequestMapping("/fileDownload")
public void fileDownload(HttpServletRequest request, HttpServletResponse response) {
String attachmentAddress = WebUtils.findString(request, "attachmentAddress");
String fileName = attachmentAddress.substring(attachmentAddress.lastIndexOf('/') + 1).replace("-", "");
InputStream inputStream = null;
try {
// 获取文件流
URL url = new URL(attachmentAddress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
byte[] content = IOUtils.toByteArray(inputStream);
// 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Cache-Control", "no-cache");
//输出文件到浏览器
WebUtils.renderFile(response, "multipart/form-data", content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
}
}
public static final void renderFile(HttpServletResponse response, String contentType, byte[] data) throws IOException {
if (data != null) {
response.setCharacterEncoding("UTF-8");
response.setContentType(contentType);
response.getOutputStream().write(data);
response.flushBuffer();
}
}
以下为几种文件转字符到方法
1.file转byte
import org.apache.commons.io.FileUtils;
byte[] bytes = FileUtils.readFileToByteArray(file);
2.InputStream转byte
import org.apache.commons.io.IOUtils;
byte[] bytes = IOUtils.toByteArray(is);
3.MultipartFile转byte
InputStream is = multiFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);
|