各位大牛!
问题1.我用spring3 mvc 的rest风格写了一个下载文件的API,现在需要把API处理后生成的文件流打包通过response发给前台,求思路或简单代码。
问题2.另外一个API实现的是处理前台上传过来的文件,(上传下载都需要识别文件类型),我这里是用http 用BODY来把文件流传输给后台,还是使用其他方法,求思路。
问题1.我用spring3 mvc 的rest风格写了一个下载文件的API,现在需要把API处理后生成的文件流打包通过response发给前台,求思路或简单代码。
问题2.另外一个API实现的是处理前台上传过来的文件,(上传下载都需要识别文件类型),我这里是用http 用BODY来把文件流传输给后台,还是使用其他方法,求思路。
@RequestMapping(value = "/download")
public void download(OutputStream os) throws IOException{
Resource res = new ClassPathResource("/image.jpg");//读取类路径下的图片文件
FileCopyUtils.copy(res.getInputStream(), os);//将图片写到输出流中
}@RequestMapping(value = "/upload")
public void upload(InputStream is) throws IOException{
File f = new File("c:\\tmp.jpg");
FileCopyUtils.copy(FileCopyUtils.copyToByteArray(is), f);//将图片写到输出流中
}
上传 肯定是post 下载一半是get细节上 你肯定要多查查spring mvc的文档了HttpEntity的话 参考下面,@RequestMapping(params = "/download", method=ResponseMethod.GET)
public ResponseEntity<byte[]> download(){
HttpHeaders headers = new HttpHeaders();
MediaType mt=new MediaType("application","octet-stream");
headers.setContentType(mt); Resource res = new ClassPathResource("/image.jpg");
byte[] fileData =FileCopyUtils.copyToByteArray(res.getInputStream()); return new ResponseEntity<String>(fileData, headers, HttpStatus.OK);
}
public String upload(HttpEntity<byte[]> httpEntity){
String contentType = httpEntity.getHeaders().getContentType();//获取文件的minitype
byte[] fileBuf = httpEntity.getBody(); File f = new File("c:\\tmp.jpg");
FileCopyUtils.copy(fileBuf, f); //保存图片
}额 楼主多查文档\百度,google 这些都是很基础的