Java:在服务器上下文外部下载文件 [英] Java : download file outside server context

查看:73
本文介绍了Java:在服务器上下文外部下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在服务器上下文外部的目录中保存文件并下载文件. 我正在使用Apache Tomacat 我可以在应用程序的webapps目录中存在的目录中执行此操作

I need to save a file and download file in directory outside server context. I am using Apache Tomacat I am able to do this in directory present in webapps directory of application

如果我的目录结构如下,

If my directory structure is as follows,

--src
--WebContent
    -- uploaddir
         -- myfile.txt

然后我就可以简单地下载了.

Then I am able to download in by simply.

      <a href="uploaddir/myfile.txt" target="_blank">download</a>

但是,问题是文件在其他目录中时说d:\\uploadedfile\\myfile.txt

But, problem is when file is in some other directory say d:\\uploadedfile\\myfile.txt

然后我将无法下载它,因为资源不在上述服务器上下文中.

then I wont be able to download it, as resource is not in server context as above.

我有uuid映射的文件路径, 喜欢,

I have file path to uuid mapping, like,

d:\\uploadedfiles\\myfile.txt <-> some_uuid

然后,我要下载文件,请点击以下链接

then I want file should be downloaded, on click of following,

   <a href="filedownloadservlet?ref_file=some_uuid">download</a>

因此,当文件不在服务器环境中时,如何使文件可下载, 我听说过getResourceAsStream()方法可以做到这一点,但是可能有人会用简单的代码片段来帮助我实现这一点吗?

So, How to make file downloadable when it is outside the server context, I heard about getResourceAsStream() method which would do this , But would any one help me on how to do this, probably with simple code snippet?

推荐答案

在这里我找到了答案,

 response.setContentType("application/msword");
 response.setHeader("Content-Disposition","attachment;filename=downloadname.doc");
 File file=new File("d:\\test.doc");
 InputStream is=new FileInputStream(file);
 int read=0;
 byte[] bytes = new byte[BYTES_DOWNLOAD];
 OutputStream os = response.getOutputStream();
 while((read = is.read(bytes))!= -1){
  os.write(bytes, 0, read);
 }
 os.flush();
 os.close();

这篇关于Java:在服务器上下文外部下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆