网上找了大量的例子原因说明都不是特别准确,今天自己结合多方方案自己总结了一下
此文案说明指的是单个文件,PS:多个文件的话,应该也是大致不差,无非是压缩解压问题,目前还没有研究到,后续有需要会补充上。
直接上码说明
1.下载
@GET
@Path("/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public void download(@Context HttpServletResponse response) {
String path = "D:/User/";
String fileName = "11.docx";
try (InputStream inputStream = new FileInputStream(new File(path, fileName));
OutputStream outputStream = response.getOutputStream();) {
//设置响应类型
response.setContentType("application/x-download");
//Content-disposition是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 Internet Explorer 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (IOException Io) {
throw new CustomWebApplicationException(Response.Status.BAD_REQUEST);
}
}
说明:因为原来都是JSON格式的包括出入所以这里要改掉,不然下载不了。
2.上传
工具都是common-io
ps:上传有两种,第一种 是spring的
@POST
@Path("/uploading")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploading(@RequestParam(value = "fileName") MultipartFile file){
String fileName = file.getOriginalFilename();
String[] filenames = fileName.split("\\.");
String uploadfileName = UUID.randomUUID() + "." + filenames[filenames.length - 1];
String noZipName = "D:/User" + "/" + uploadfileName;
File file1 = new File(noZipName);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
} catch (IOException e) {
throw new CustomWebApplicationException(Response.Status.BAD_REQUEST);
}
}
第二种则是基于jersey的
@POST
@Path("/uploading1")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadFile(@FormDataParam("fileName") InputStream fileInputStream,
@FormDataParam("fileName") FormDataContentDisposition disposition
, @Context ServletContext ctx) throws Exception {
File upload = new File("D:/User/",
UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(disposition.getFileName()));
try {
FileUtils.copyInputStreamToFile(fileInputStream, upload);
} catch (IOException e) {
e.printStackTrace();
}
}
不过第二种要引入包以及其他配置
<!--Jersey上传引入-->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
切记: 不要加版本号,不然会有冲突。貌似是2.0版本的相关引入删除导致的以及配置下图的引入执行。
上传的话,个人喜欢第一个,因为不需要那么多的配置以及引入,不过从专业角度考虑的话,毕竟是基于jersey,第二个显的更专业性。