2013-04-02 20 views
6

Tôi mới sử dụng công nghệ JAVA, đặc biệt là Servlets.I cần tạo một dự án ứng dụng web có tải lên và tải xuống tệp từ/đến máy chủ (tomcat). Tôi đã tải lên servlet, hoạt động tốt.Servlet để tải xuống tệp từ một thư mục cụ thể?

tôi cũng có một servlet tải xuống, được tìm thấy trên internet. Nhưng vấn đề là servlet này chỉ cho phép tải xuống một tệp cụ thể và đường dẫn đến tệp cụ thể này được cung cấp trong servlet. Tôi cần cho phép khách hàng xem toàn bộ nội dung của thư mục tải lên của tôi và chọn tệp mà anh ấy muốn tải xuống từ thư mục này.

Mã của servlet tải về là thế này:

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(); 
} 
} 

Các trang JSP là thế này:

<%@ 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> 

tôi đã tìm kiếm rất nhiều servlets nhưng tất cả đều là như thế này ... họ cho phép tải xuống chỉ một tệp cụ thể. Có ai giúp tôi không? Cảm ơn bạn rất nhiều!

+0

bạn đã làm gì cố gắng? Bạn đã thực hiện bất kỳ sửa đổi nào đối với mã bạn đã tải xuống chưa? Bạn đã thực hiện những thay đổi nào? Những gì đã làm việc? Cái gì không? Bạn đã thực hiện bất kỳ nghiên cứu nào ngoài việc tìm kiếm một giải pháp hoàn chỉnh mà bạn có thể tải xuống? Chỉ cần sao chép và dán mã từ internet sẽ không giúp bạn có được rất nhiều, bạn sẽ phải làm công việc của riêng bạn đôi khi. – Adrian

+0

@Adrian Cảm ơn bạn đã trả lời. Như tôi đã nói, đoạn mã trên chỉ hoạt động tốt khi tải xuống một tệp được cung cấp dưới dạng đường dẫn đến nó trong Servlet.In ví dụ này, trong hàm init(). Tôi đã thử cung cấp đường dẫn dưới dạng chuỗi cho thuộc tính filePath.example: filepath = "C: // Apache // Application // data //", nhưng tôi đã nhận được lỗi: Truy cập bị từ chối. Tôi đã thử một thứ khác: để tạo danh sách nội dung của thư mục trong JSP của tôi với thuộc tính tệp và phương thức listFiles, sau đó tôi viết '
<% = file.getName()%> 'nhưng chỉ hoạt động trong IE với mục tiêu lưu dưới dạng. –
AdiCrainic

+0

@ user2236267 thử sử dụng một đường dẫn khác, như * C: \\ external \\ path *. Ngoài ra, hãy đảm bảo người dùng của bạn có đủ quyền để ghi vào thư mục đó. Tôi không bao gồm thông tin đó vì tôi cho rằng bạn đã biết nó. –

Trả lời

6

Vì bạn đang xử lý dữ liệu theo phương pháp doGet, bạn có thể chuyển tham số tới servlet nơi bạn chỉ định tên của tệp bạn muốn tải xuống. Đối với điều này, bạn nên giả định rằng tên tệp tồn tại trong đường dẫn cơ sở của bạn. Mã này có thể đi như thế này:

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 
    } 
} 

Lưu ý rằng kể từ khi mã bây giờ sử dụng File(String parent, String child) constructor, filePath bạn không nên chứa các dấu phân cách nữa (điều này sẽ được Java xử lý):

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

** Cảm ơn bạn rất nhiều vì câu trả lời của bạn ** Tôi đã thử mã của bạn nhưng tôi không thể làm cho nó hoạt động. – AdiCrainic

+0

@ user2236267 dùng thử. Nếu nó phù hợp với nhu cầu của bạn, vui lòng đánh dấu chọn bên dưới danh tiếng để đánh dấu bài đăng là câu trả lời. –

+0

Tôi mới vào stackoverflow.it sẽ mất một thời gian để tôi làm việc với điều này. Tôi đã cố gắng bỏ phiếu cho câu trả lời của bạn nhưng nó nói với tôi rằng tôi cần 15 danh tiếng. Tôi muốn trả lời bằng mã mới của mình, nhưng nó nói rằng nhận xét của tôi quá lớn. – AdiCrainic

1

bạn có thể làm như thế

 public void doGet(HttpServletRequest req, HttpServletResponse res){ 
    res.setContentType("text/html); 
     PrintWriter out=response.getWriter(); 
     String fileName="home.txt"; 
     String filePath="d:\\"; 
    response.setContentType("APPLICATION/OCTET-STREAM"); 
    response.setHeader("Content-Disposition","attachment;fileName=\""+fileName+"\""); 
    int i; 
    FileInputStream file=new FileInputStream(filePath +fileName); 
    while((i=file.read()) !=-1){ 
     out.write(i); 
    } 
    file.close(); 
    out.close(); 
} 
0
// get MIME type of the file 
    String mimeType = context.getMimeType(fullPath); 
    if (mimeType == null) { 
     // set to binary type if MIME mapping not found 
     mimeType = "application/octet-stream"; 
    } 
    System.out.println("MIME type: " + mimeType); 

    // set content attributes for the response 
    response.setContentType(mimeType); 
    response.setContentLength((int) downloadFile.length()); 

này chi tiết hơn và câu hỏi làm thế nào để cải thiện: https://stackoverflow.com/questions/41914092/how-change-servlet-which-download-single-file-but-can-folderfew-files-in-fold

Các vấn đề liên quan