如何使用Rest API Web服务从资源文件夹下载多个文件?

时间:2018-12-24 06:50:40

标签: spring-boot

我正在尝试使用Spring Boot从Web服务下载2个文件。但是,当我尝试访问以下URL [http://localhost:8080/download/pdf]时,只会下载“ Template1.xlsx”。这里是我用于下载Web服务的控制器方法,

private static final String INTERNAL_FILE="Template1.xlsx";
private static final String INTERNAL_FILE1="Template2.xlsx";

@RequestMapping(value="/download/{type}", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response, @PathVariable("type") String type) throws IOException {
    List<File> fileList = new ArrayList<>();
    File file = null, file1 = null;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    file = new File(classloader.getResource(INTERNAL_FILE).getFile());
    fileList.add(file);
    ClassLoader classloader1 = Thread.currentThread().getContextClassLoader();
    file1 = new File(classloader1.getResource(INTERNAL_FILE1).getFile());
    fileList.add(file1);
    for(int i=0;i<fileList.size(); i++) {
        File f = fileList.get(i);
        if(!f.exists()){
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }
        String mimeType= URLConnection.guessContentTypeFromName(f.getName());
        if(mimeType==null){
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }
        System.out.println("mimetype : "+mimeType);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + f.getName() +"\""));
        response.setContentLength((int)f.length());
        System.out.println("download file name ------ "+f.getName());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(f));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }
}

我想下载两个文件。我是春季靴的新手。有人可以建议我实现这个目标吗?预先感谢

0 个答案:

没有答案