Javascript Servelt使用contextPath和servletContext上载任何文件上载成功下载即可';t下载
我使用以下方式完成了文件上传:Javascript Servelt使用contextPath和servletContext上载任何文件上载成功下载即可';t下载,javascript,java,servlets,Javascript,Java,Servlets,我使用以下方式完成了文件上传: ServletContext servletContext = getServletContext(); String contextPath = servletContext.getRealPath(File.separator); String path = contextPath + "\\uploads\\" + session.getAttribute("seusername");
ServletContext servletContext = getServletContext();
String contextPath = servletContext.getRealPath(File.separator);
String path = contextPath + "\\uploads\\" + session.getAttribute("seusername");
System.out.println(path);
File file=new File(path);
if(!file.exists())
file.mkdirs();
Part filePart = request.getPart("uploadfile");
//return content type of the file
String type = filePart.getHeader("content-type");
//checking content type of file.
if (!type.equals("application/x-msdownload")) {
final String fileName = getFileName(filePart);
myfilename=fileName;
try {
EncriptFilename= aESCryp.encrypt(fileName);
System.out.println(EncriptFilename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream fout = null;
InputStream filecontent = null;
try {
fout = new FileOutputStream(new File(path + File.separator + fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[32 * 1024];
while ((read = filecontent.read(bytes)) != -1) {
fout.write(bytes, 0, read);
}
fout.flush();
fout.close();
} catch (Exception er) {
System.out.println("error:"+er.getMessage());
}
}
我上传的图像,pdf,文档文件,,,它是好的。。
在我的本地光盘文件夹上的文件位置之后。
D:\JavaWorkspace.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\File\uploads\user\java\u coffee\u cup\u logo1600.png
我的问题是…如何下载这个文件,,,
我无法使用href link下载..您的web应用程序可以支持文件下载,这与您文章中的
Servlet
所做的完全相反
创建“下载”Servlet
,并在web.xml
中配置到Servlet
的映射(或使用注释定义映射)。此servlet的URL可能如下所示:
在下载Servlet
中,查看请求URL以发现请求的文件名(my file.jpg
),然后使用FileInputStream
打开并读取my file.jpg
request.getPathInfo()
可能会为您提供确定用户要下载的文件所需的信息。见
请注意,my file.jpg
可以存在于您想要的任何地方。您的Servlet
可以将请求URL中的文件名和路径映射到本地文件系统中的任意位置。该文件甚至可能存在于另一个web服务器上。您只需要能够创建一个访问该文件的InputStream
使用该文件的路径信息,创建一个FileInputStream
来访问该文件。然后将FileInputStream
复制到ServletResponse
的输出流。这和这两个示例给出了如何将InputStream
复制到OutputStream
您可以像这样获得响应的输出流:response.getOutputStream()
。完成后,不要忘记关闭InputStream
和OutputStream