我是Java Servlets / Apache Tomcat / etc的新手,但我能找到一些方便的资源来说明如何实现下载和上传功能。
当用户想要上传文件时,他们会单击该按钮,系统会提示他们选择文件。但是,当他们想要下载文件时,他们只能选择一个文件(在servlet中指定)。
所以,我的问题是:有没有办法以某种方式列出目录,让用户选择一个特定的文件,然后下载该文件?
如果你需要一个参考点,下面是我的代码:
注意:此代码有效,我只是想知道如何以我想要的效果扩展它。
package testPackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet
{
private static final String absFilePath = "/test/files/download/test.txt";
private static final String relFilePath = "/files/download/test.txt";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Quick switch to determine what type of path to user
boolean useAbsolute = false; //Defaults to relative
//Initialize a new File
File downloadFile = new File("");
//Check if we want to use the absolute file path
if(useAbsolute)
{
//Read the input file from the absolute path
downloadFile = new File(absFilePath);
}
//Otherwise, we are using relative
else
{
//Read the input file from the relative path
String relativePath = getServletContext().getRealPath(relFilePath);
downloadFile = new File(relativePath);
//System.out.println("Relative Path: " + relativePath);
}
//Open up the FileInputStream
FileInputStream inputStream = new FileInputStream(downloadFile);
//Obtain the Servlet Context
ServletContext context = getServletContext();
//Get the MIME type of the file
String mimeType = context.getMimeType(absFilePath);
//If we don't get a type, default to binary
if(mimeType == null)
{
//Set to binary type if the MIME mapping is not found
mimeType = "application/octet-stream";
}
//Just some logging
System.out.println("MIME Type: " + mimeType);
//Modify Servlet Response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
//Set the header key/value
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
//Obtain the response output stream
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
//While there are bytes to write
while((bytesRead = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
//Close the streams
inputStream.close();
outputStream.close();
}
}