我想从互联网上下载文件,我有该文件的网址。所以我写了一个下载servlet:
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathToDownload = request.getParameter("url");
URL url = new URL(pathToDownload);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
InputStream is = uc.getInputStream();
response.setContentType(contentType);
// resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
在这里我想在用户点击文件时显示是否保存弹出窗口,以便
resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
但我希望文件名与internate上的文件名相同,所以另外在上面的代码片段需要什么?
答案 0 :(得分:0)
将子字符串从最后一个“/”剪切到URL字符串的末尾 - 这是您的文件名。
答案 1 :(得分:0)
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index != 0) {
fileName = disposition.substring(index + 9,
disposition.length());
}
} else {
// extracts file name from URL
fileName = link.substring(link.lastIndexOf("/") + 1,
link.length());
}