swagger传递文件对象file

先在swagger-editor中定义访问路径:java

必定要定义produces为你所须要返回的mime类型,mime类型参考:http://www.w3school.com.cn/media/media_mimeref.aspwindows

选择生成server端代码:api

这里我选择的是jaxrs,是某个平台的java代码,具体是哪一个平台没去研究浏览器

生成号代码以后,会有这样的代码测试

解压以后,用intellij打开该目录:ui

须要完善的代码都在impl里,里面是空代码:url

具体如何调用,参考client端代码:orm

这样就配置好了,固然,我这里用得是jetty嵌入式开发,比较方便server

继续话题,当jetty起来以后,好比本机的地址是localhost:33890,那么在测试代码里须要设置basePath,对象

@Test
public void downloadGetTest() throws ApiException {
    String ddd= "111";
    String ddd= "aaa";
    String ddd= "zzz";
    api.getApiClient().setBasePath("http://localhost:33890");
    File response = api.downloadGet(ddd, ddd, ddd);
    System.out.println(response);
    // TODO: test validations
}

这样请求就发过去了,server端impl/downloadimpl代码以下:

public Response downloadGet(String ddd, String ddd, String ddd, SecurityContext securityContext) throws NotFoundException {
    String filename = ddd+ "-" + ddd+ "-" + ddd;
    String path = "http://yjsy.cupl.edu.cn/attachments/article/2689/2017%E5%B9%B4%E7%A1%95%E5%A3%AB%E7%A0%94%E7%A9%B6%E7%94%9F%E7%BB%9F%E8%80%83%E6%8B%9F%E6%8B%9B%E7%94%9F%E8%AE%A1%E5%88%92.pdf";
    byte[] getData = null;
    File tempFile = null;
    try {
        URL url = new URL(path);
        // 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的链接。
        URLConnection uc = url.openConnection();
        //读取文件
        InputStream in = uc.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = in.read(b)) != -1) {
            System.out.println("------ process continue -------");
            bos.write(b, 0, len);
        }
        bos.close();
        getData = bos.toByteArray();
        //这里能够指定存到windows上的路径,必定要是已存在的目录
        File directory = new File("d:\\");
        //写文件
        tempFile = File.createTempFile(filename, ".pdf", directory);
        tempFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempFile);
        fos.write(getData);
        System.out.println(tempFile.length());
        in.close();
        fos.close();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return Response.ok().entity(tempFile).build();
}

Response是swagger生成的一个抽象类

执行请求后,在本地d盘下就会生成一个pdf的文件,同时在c盘的临时文件夹下也会生成一样的文件

C:\Users\jack\AppData\Local\Temp\download-1392513126829992389

若是使用浏览器访问,也能在浏览器上显示出pdf的内容,以下:

相关文章
相关标签/搜索