您的位置:首页 > 理论基础 > 计算机网络

springmvc框架下hdfs下载文件流直接发送httpresponse

2016-08-03 09:25 232 查看
1、首先是通过hdfs上的路径或者inputstream:

public InputStream downLoadFile(final String video_unique, String hdfsPath) throws IOException {
FileSystem fileSystem = FileSystem.get(conf);
InputStream inputStream = fileSystem.open(new Path(hdfsPath));
return inputStream;
}


2、然后用一个接口调用的这个方法(我自己的需求你们可以省略):

public InputStream doVideoDownload(String video_unique) throws IOException {
HDFSUtils hdfsUtils = new HDFSUtils();
String hdfsPath = getVideoInfoFieldByVideoUnique(video_unique).getUpload_url() + "/"
+ getVideoInfoFieldByVideoUnique(video_unique).getVideo_name();
InputStream inputStream = hdfsUtils.downLoadFile(video_unique, hdfsPath);
return inputStream;
}


3、controller访问:

@RequestMapping(value = "/fileDownload", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public Object fileDownloadDo(String video_unique, HttpServletResponse response) throws IllegalStateException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
InputStream inputStream = null;
inputStream = iVideoCloudService.doVideoDownload(video_unique);
OutputStream os = response.getOutputStream();
byte[] b = new byte[4096];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
return null;
}


4、跟上传文件一样配置dispatchservlet,不过这里我上传文件配置了进度监听,所以是自己的类:

<!-- SpringMVC上传文件时,为了获取上传进度,装载自定义MultipartResolver处理器 -->
<bean id="multipartResolver" class="com.eshore.storage.utils.CustomMultipartResolver">
<property name="maxUploadSize" value="10000000000"/>
<property name="maxInMemorySize" value="4096"/>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>


5、当然,也可以吧文件读写的程序放在接口实现里,相应的controller也修改并简化:

public Object doVideoDownload(String video_unique, OutputStream outputStream) throws IOException {
HDFSUtils hdfsUtils = new HDFSUtils();
String hdfsPath = getVideoInfoFieldByVideoUnique(video_unique).getUpload_url() + "/"
+ getVideoInfoFieldByVideoUnique(video_unique).getVideo_name();
InputStream inputStream = hdfsUtils.downLoadFile(video_unique, hdfsPath);
byte[] b = new byte[4096];
int length;
while ((length = inputStream.read(b)) > 0) {
outputStream.write(b, 0, length);
}
outputStream.close();
inputStream.close();
return null;
}
@RequestMapping(value = "/fileDownload", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public Object fileDownloadDo(String video_unique, HttpServletResponse response) throws IllegalStateException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
OutputStream outputStream = response.getOutputStream();
return iVideoCloudService.doVideoDownload(video_unique, outputStream);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: