如何从http URL下载文件

时间:2015-04-28 04:55:00

标签: java

这是我下载文件的servlet代码。但它只下载本地文件我想从http url下载文件,如:“(http://www.java2s.com/Code/JarDownload/sqljdbc4/sqljdbc4-3.0.jar.zip”)。

package net.codejava;

 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.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  public class DownloadFileServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // reads input file from an absolute path
    String filePath = "E:/Test/Download/MYPIC.JPG";
    File downloadFile = new File(filePath);
    FileInputStream inStream = new FileInputStream(downloadFile);

    // if you want to use a relative path to context root:
    String relativePath = getServletContext().getRealPath("");
    System.out.println("relativePath = " + relativePath);

    // obtains ServletContext
    ServletContext context = getServletContext();

    // gets MIME type of the file
    String mimeType = context.getMimeType(filePath);
    if (mimeType == null) {         
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // modifies response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // forces download
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment;  
     filename=\"%s"",downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // obtains response's output stream
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inStream.close();
    outStream.close();      
       }
    }

2 个答案:

答案 0 :(得分:1)

public class DownloadServlet extends HttpServlet {
/**
 * 
 */
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse 
   response) throws ServletException, IOException {

    /*final GetData data = new HttpGetData();
    String downloadFile=data.getContent("http://www.java2s.com
      /Code/JarDownload/spring-/spring-2.5.jar.zip");
    System.out.println("download file is:"+downloadFile);*/
    String filePath = "http://www.java2s.com/Code/JarDownload/spring-
      /spring-2.5.jar.zip";
        //URL url = new URL(filePath);
        //Scanner scan = new Scanner(System.in);
        //filePath=scan.nextLine();
     URL url = new URL(filePath);
        HttpURLConnection httpConn = (HttpURLConnection) 
         url.openConnection();
       //File downloadFile = new File(filePath);
        //FileInputStream inStream = new FileInputStream(downloadFile);

        InputStream inStream = httpConn.getInputStream();

        // if you want to use a relative path to context root:
        String relativePath = getServletContext().getRealPath("");
        System.out.println("relativePath = " + relativePath);

        // obtains ServletContext
        ServletContext context = getServletContext();

        // gets MIME type of the file
        String mimeType = context.getMimeType(filePath);
        if (mimeType == null) {         
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // modifies response
        response.setContentType(mimeType);
        response.setContentLength((int) httpConn.getContentLength());

        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,
                filePath.length());

        // forces download
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",
         fileName);
        response.setHeader(headerKey, headerValue);

        // obtains response's output stream
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        inStream.close();
        outStream.close(); 
            }

         }

答案 1 :(得分:0)

首先确保您的防火墙没有阻止您的应用程序。 您可以在Apache中使用FileUtils类将url下载为文件。

FileUtils.copyURLToFile(your_URL, file);