這是我下載文件的servlet代碼。但其下載只有本地文件,我想從http url下載文件,如:
(「http://www.java2s.com/Code/JarDownload/sqljdbc4/sqljdbc4-3.0.jar.zip」)。如何從http URL下載文件
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();
}
}
我什麼也看不到在你的代碼,從一個網址下載。您打開一個本地文件並在servlet響應中返回此文件的內容。您是否希望servlet不打開本地文件,而是從URL下載**並且**在servlet響應中返回下載文件的內容? –