protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
PrintWriter out=response.getWriter();
String examId=request.getParameter("source");
session.setAttribute("dur",examId);
String fileName = examId+".zip";
List<String> filesListInDir = new ArrayList<String>();
File dir = new File("C:/Temp/Answers"); // Our source file
File[] files = dir.listFiles();
int flag=0;
for(File file : files){
if(file.isFile()){
response.setContentType("APPLICATION/zip");
String disHeader = "zip";
response.setHeader("Content-Disposition", disHeader);
filesListInDir.add(file.getAbsolutePath());
if(file.getName().equalsIgnoreCase(fileName)){
flag = 1;
session.setAttribute("fileName", file.getName());
FileInputStream fileInputStream = new FileInputStream(file.getPath());
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
}
if(flag == 0){
System.out.println("file not match");
out.print("Answer is not uploaded");
}
}
}
答案 0 :(得分:0)
您的代码中存在一些问题。
1-让我们假设您所读的内容已经是zip文件。
在这种情况下,您应更改response.setContentType
和response.setHeader
部分,如下所示
response.setContentType("application/zip");
response.setHeader("Content-Disposition","inline; filename=" + fileName );
2-您在文件夹中循环并尝试为文件夹中的每个文件发送一次响应标头(contentType和内容处置)。这应该会生成一个&#34;已经发送的标题&#34;第一个文件发送后,服务器发生异常。所以你应该做这样的事情
int flag=0;
for(File file : files){
if(file.isFile()){
filesListInDir.add(file.getAbsolutePath()); // what is the utility of this ??
if(file.getName().equalsIgnoreCase(fileName)){
flag = 1;
response.setContentType("application/zip");
response.setHeader("Content-Disposition","inline; filename=" + fileName );
session.setAttribute("fileName", file.getName());
FileInputStream fileInputStream = new FileInputStream(file.getPath());
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}//closes while
fileInputStream.close();
out.close();
return; //you finished if you sent the file
} // closes if(file.getName().equalsIgnoreCase(fileName))
} // closes if(file.isFile())
}// closes for
//following block moved after the for so it prints at most once
if(flag == 0){
System.out.println("file not match");
out.print("Answer is not uploaded");
}