问题描述:
一个文件上传后,下载时如果不是压缩文件需要把一个文件打包成zip文件返回给前端;下载时如果是压缩文件直接返回给前端
问题解决:
传入源文件的路径,返回打包后文件的路径
1.java实现FileService层
public String zipFile(String path) throws FileNotFoundException {
File file = new File(path);
File zipfile = new File(COURSE_META_DOC_SUBDIR,file.getName().substring( 0 , file.getName().lastIndexOf("."))+".zip");
System.out.println("zip path"+zipfile.getAbsolutePath());
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipfile));
FileInputStream input = new FileInputStream(file);
int temp = 0;
try {
zipOut.putNextEntry(new ZipEntry(file.getName()));
while(( temp = input.read())!= -1) {
zipOut.write(temp);
}
} catch (IOException e) {
System.out.println("error1");
}finally {
try {
input.close();
zipOut.close();
//file.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error2");
}
}
return zipfile.getAbsolutePath();
}
2.具体业务层CourseService层
如果文件名的后缀不是zip或rar,将他压缩;如果是,直接读取文件。最后以二进制流返回给controlll
public byte[] getFile(String path) throws IOException {
File file = null;
if (fileService.getSuffix(path) != "zip" || fileService.getSuffix(path) != "rar") {
String zipPath = fileService.zipFile(path);
System.out.println("current file path " + path);
file = new File(zipPath);
// 把文件压缩成zip
} else {
file = new File(path);
}
if (!file.exists())
throw new BusinessException(String.format("课程附件路径'%s'对应的文件不存在", path), ErrorCode.E00001);
byte[] bb = FileUtils.readFileToByteArray(file);
return bb;
}
3.controller层
@RequestMapping(value = COURSE_API + "/file", method = GET)
@ResponseBody
public byte[] getAccessory(@RequestParam String path) throws IOException {
return service.getFile(path);
}
4.前端js
使用自定义文件导出函数导出文件
function downloadFile(){
courseDao.getFile(vm.course.accessory, function (response) {
var name = vm.course.accessory.substring(vm.course.accessory.lastIndexOf("\\")+1,vm.course.accessory.length);
FileExport.export(response,
"application/force-download;",
name);
});
}