文件下载
结合网上一些博客修改的 具体哪些太久了,记不清了
package com.cj.core.utils.download;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* @author: 刘磊
* @Description: 文件下载
* @date: 2019/7/5 17:19
**/
@Slf4j
public class DownUtil {
/**
* 下载word
* urls 网址
*/
public static String downWord(String urls, String fileName, HttpServletResponse resp) throws IOException {
//获取文件长度
Long nFileLength = getFileSize(urls);
System.out.println("文件长度---->" + nFileLength);
if (nFileLength == -1) {
System.out.println("文件长度未知!");
return "文件长度未知!";
} else if (nFileLength == -2) {
System.out.println("文件不可访问!");
return "文件不可访问!";
}
//设置输出文件地址和名字
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
// fileName = new String(fileName.getBytes(), "UTF-8");
log.info("++++++++" + fileName + "++++++++");
resp.setCharacterEncoding("UTF-8");
//设置响应头application/msword
resp.setHeader("content-Type", "application/msword;charset=UTF-8");
resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx;filename*=UTF-8''" + fileName + ".docx");
// resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx;filename*=ISO-8859-1''" + fileName + ".docx");
// resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx");
resp.setCharacterEncoding("UTF-8");
resp.setContentLength(nFileLength.intValue());
// 定义输出类型 msword word
resp.setContentType("application/msword");
OutputStream out = resp.getOutputStream();
URL url = new URL(urls);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("User-Agent", "NetFox");
String sProperty = "bytes=0-";
httpConnection.setRequestProperty("RANGE", sProperty);
InputStream input = httpConnection.getInputStream();
//输出文件
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = input.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.close();
System.out.println("文件下载结束!");
return "文件下载结束!";
}
//获得文件长度
public static long getFileSize(String urls) {
int nFileLength = -1;
try {
URL url = new URL(urls);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("User-Agent", "NetFox");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400) {
return -2; //-2 represent access is error
}
String sHeader;
for (int i = 1; ; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
break;
}
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return nFileLength;
}
}