我需要从文件夹下载文件,为此我创建了这个servlet DownloadServlet.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
File f = new File("C:/apache-tomcat-7.0.27/webapps/data");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++){
String filename=files[i].getName();
String filepath=files[i].getAbsolutePath();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath);
int j;
while ((j=fileInputStream.read()) != -1) {
out.write(j);
}
fileInputStream.close();
out.close();
}
}
}
上述代码用于下载程序。 我创建的html文件如下:
在服务器上运行html文件时,只显示一个下载链接,下载该文件夹中的第一个文件。
任何人都可以帮助我如何显示所有文件的链接????