用于从特定文件夹下载文件的Servlet? [英] Servlet for download files from a specific folder?

查看:109
本文介绍了用于从特定文件夹下载文件的Servlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢JAVA技术,特别是Servlets.I我需要制作一个Web应用程序项目,它有一个上传和下载文件到/从服务器(tomcat)。我已经有一个上传的servlet,工作正常。 / p>

我还有一个在互联网上找到的下载servlet,但是问题是这个servlet允许只下载一个特定的文件,并且这个特定文件的路径在servlet。我需要让客户端看到我的上传文件夹的所有内容,并选择要从该文件夹下载哪个文件。



下载servlet的代码是:

  import java.io.DataInputStream; 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class DownloadServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private static final int BUFSIZE = 4096;
private String filePath;`

public void init(){
//文件data.xls在Web应用程序文件夹下

filePath = getServletContext ().getRealPath()+ File.separator; // +data.xls;
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,IOException {
文件文件= new File(filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
ServletContext context = getServletConfig()。getServletContext();
String mimetype = context.getMimeType(filePath);

//设置响应内容类型
if(mimetype == null){
mimetype =application / octet-stream;
}
response.setContentType(mimetype);
response.setContentLength((int)file.length());
String fileName =(new File(filePath))。getName();

//设置HTTP头
response.setHeader(Content-Disposition,attachment; filename = \+ fileName +\);

byte [] byteBuffer = new byte [BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));

//读取文件的字节并将其写入响应流
while((in = null)&((length = in.read(byteBuffer))!= -1))
{
outStream.write(byteBuffer,0,length);
}

in.close();
outStream.close();
}
}

JSP页面是这样的:

 <%@ page language =javacontentType =text / html; charset = ISO-8859-1
pageEncoding = ISO-8859-1 %>
<!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 Transitional // ENhttp://www.w3.org/TR/html4/loose.dtd\">
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = ISO-8859-1>
< title>下载Servlet测试< / title>
< / head>
< body>
点击链接下载:< a href =DownloadServlet>下载链接< / a>
< / body>
< / html>

我搜索了很多servlet,但都是这样的...他们只允许下载一个具体文件。
任何人都可以帮我吗?
非常感谢!

解决方案

由于您正在处理 doGet上的数据方法,您可以将参数传递到指定要下载的文件的名称的servlet。为此,您应该假定文件名存在于您的基本路径中。代码可以这样:



HTML

 <身体GT; 
点击链接下载:
< a href =DownloadServlet?fileName = data.xls>下载链接< / a>
< / body>

Java Servlet代码:

  protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,IOException {
//通过名称检索参数
String fileName = request.getParameter(文件名); //这将返回`data.xls`
//使用File(parent,child)构造函数为File class
File file = new File(filePath,fileName);
//验证文件是否存在
if(file.exists()){
//移动代码下载您的文件在这里...

} else {
//处理一个不做任何事情的回应
}
}

请注意,由于代码现在使用 文件(String parent,String child) 构造函数,您的 filePath 不应该包含分隔符(这将由Java处理):

  public void init ){
//文件data.xls在web应用程序文件夹下
filePath = getServletContext()。getRealPath();
}


I am new to JAVA technology,especially Servlets.I need to make a Web application project which have an upload and a download files to/from a server(tomcat).I have already an upload servlet,which works fine.

i have also a download servlet,found on the internet.But the problem is that this servlet allows downloading only a specific file,and the path to this specific file is given in the servlet. I need to let the client see the entire content of my upload folder and select which file he wants to download from this folder.

The code of the download servlet is this:

import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext; 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



 public class DownloadServlet extends javax.servlet.http.HttpServlet implements
            javax.servlet.Servlet {
        static final long serialVersionUID = 1L;
        private static final int BUFSIZE = 4096;
        private String filePath;`

public void init() {
    // the file data.xls is under web application folder

    filePath = getServletContext().getRealPath("")  + File.separator;// + "data.xls";
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    File file = new File(filePath);
    int length   = 0;
    ServletOutputStream outStream = response.getOutputStream();
    ServletContext context  = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(filePath);

    // sets response content type
    if (mimetype == null) {
        mimetype = "application/octet-stream";
    }
    response.setContentType(mimetype);
    response.setContentLength((int)file.length());
    String fileName = (new File(filePath)).getName();

    // sets HTTP header
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    byte[] byteBuffer = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(file));

    // reads the file's bytes and writes them to the response stream
    while ((in != null) && ((length = in.read(byteBuffer)) != -1))
    {
        outStream.write(byteBuffer,0,length);
    }

    in.close();
    outStream.close();
}
}

The JSP page is this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download Servlet Test</title>
</head>
<body>
Click on the link to download: <a href="DownloadServlet">Download Link</a>
</body>
</html>

I searched a lot of servlets but all of them were like this...they allowed downloading only a specific file. Can anyone help me? Thank you very much!

解决方案

Since you're handling the data on the doGet method, you can pass a parameter to the servlet where you indicate the name of the file you want to download. For this, you should assume that the file name exists in your base path. The code could go like this:

HTML

<body>
    Click on the link to download:
    <a href="DownloadServlet?fileName=data.xls">Download Link</a>
</body>

Java Servlet Code:

protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    //retrieving the parameter by its name
    String fileName = request.getParameter("fileName"); //this will return `data.xls`
    //using the File(parent, child) constructor for File class
    File file = new File(filePath, fileName);
    //verify if the file exists
    if (file.exists()) {
        //move the code to download your file inside here...

    } else {
        //handle a response to do nothing
    }
}

Note that since the code now uses File(String parent, String child) constructor, your filePath should not contain the separator anymore (this will be handled by Java):

public void init() {
    // the file data.xls is under web application folder
    filePath = getServletContext().getRealPath("");
}

这篇关于用于从特定文件夹下载文件的Servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆