公司的门户网站需要实现文件上传下载功能。
在实现下载功能后,测试txt文件,下载成功。但是doc和图片等文件下载后,出现内容缺失问题。
以下为下载功能代码:
public class LayUiDownload extends HttpServlet {
/**
* Constructor of the object.
*/
public LayUiDownload() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public synchronized void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String params=request.getParameter("params");
//Map<String, String[]>maps = request.getParameterMap();
String URL=params.substring(8,params.lastIndexOf("\""));
//URL=URL.replace("\\\\", "/");
String ori_url=URL;
String URL0=URL.substring(0,URL.lastIndexOf("/")+1);
String URL1=URL.substring(URL.lastIndexOf("/")+1);
URL1 = URLEncoder.encode(URL1, "UTF-8");
URL=URL0+URL1;
File file = null;
try {
// 统一资源
String urlPath =URL;
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000*5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String fileFullName = ori_url.substring(ori_url.lastIndexOf("/")+1);
// 指定存放位置
String path = "D:\\Program Files\\file" + File.separatorChar + fileFullName;
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
}
System.out.println("C:"+ File.separatorChar + urlPath.substring(urlPath.lastIndexOf("/")).split("/")[1]);
bin.close();
out.close();
System.out.println("文件下载成功!");
} catch (Exception e) {
System.out.println("文件下载失败!");
e.printStackTrace();
}finally {
System.out.println("文件下载结束!");
}
}
}
截图:
上传的正常文件:
下载的问题文件:
下载的问题图片文件:
问题已解决,原因是配置中对资源的访问只有TXT类型做了配置,其他类型文件的下载请求都被登录界面拦截了,多谢回答
out.flush()试试
试试
直接用 httpURLConnection.getInputStream()
不要用 new BufferedInputStream