3
Я хочу, чтобы загрузить файл с сервера, и я определяю файл чванство следующим образом:Развертывание Swagger, как указать, что файл возвращается?
swagger: '2.0'
################################################################################
# API Information
################################################################################
info:
version: v0
title: XXX REST API
host: api.xxx.io
basePath: /v0
schemes:
- http
- https
produces:
- application/json
################################################################################
# Security
################################################################################
################################################################################
# Parameters
################################################################################
parameters:
productId:
name: productId
in: path
description: The product identifier
type: string
required: true
################################################################################
# Paths
################################################################################
paths:
/products:
get:
description: Get the list of products
operationId: getProducts
responses:
200:
description: OK
schema:
type: array
items:
$ref: '#/definitions/Product'
/resources/{productId}:
parameters:
- $ref: '#/parameters/productId'
get:
description: Get resources of a product
operationId: getResourcesByProductId
produces:
- application/octet-stream
responses:
200:
description: OK
schema:
type: file
################################################################################
# Definitions
################################################################################
definitions:
Product:
type: object
required:
- id
properties:
id:
type: string
name:
type: string
category:
type: array
items:
type: string
description:
type: string
price:
type: number
thumbnailUri:
type: string
previewUris:
type: array
items:
type: string
resources:
type: array
items:
$ref: '#ResourceMeta'
И апи выглядит следующим образом:
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-24T17:56:03.446+08:00")
@Controller
public class ResourcesApiController implements ResourcesApi {
public ResponseEntity<File> getResourcesByProductId(
@ApiParam(value = "The product identifier",required=true) @PathVariable("productId") String productId
) {
// do some magic!
return new ResponseEntity<File>(HttpStatus.OK);
}
}
Мой контроллер выглядит следующим образом:
@Controller
public class ResourceController implements ResourcesApi {
private final Logger logger = Logger.getLogger(ResourceController.class);
// @RequestMapping(value="/resources/{productId}", method= RequestMethod.GET)
public ResponseEntity<File> getResourcesByProductId(@ApiParam(value = "The product identifier", required = true) @PathVariable("productId") String productId) {
String path = "resources" + File.separator + productId;
File file = new File(path);
FileSystemResource fileSystemResource = new FileSystemResource(file);
InputStreamResource inputStreamResource = null;
try {
inputStreamResource = new InputStreamResource(fileSystemResource.getInputStream());
} catch (IOException e) {
logger.error(e.toString());
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.body(file);
}
}
Однако, когда я запускаю приложение, оно возвращает файл, но содержит только метаданные файла, а не его содержание. Как я могу заставить его вернуть содержимое файла? ! Спасибо
Да, я знаю, что с помощью inputstreamresource возвращает содержимое файла. Но как определить положительный api в первом файле? Теперь, согласно моему определению в первом файле, он генерирует функцию, которая возвращает ResponseEntity не ResponseEntity , как во втором файле ... –
Niubility
Не имеет большого смысла возвращать файл непосредственно в качестве ответа. Как вы обнаружили, объект File - это просто контейнер для пути и метаданных для фактического файла в файловой системе, он не содержит содержимого файла. Итак, если вы отправляете пользователю объект 'File ("/root/dev/file.txt ")', то он получит объект 'File', но он будет указывать на путь' /root/dev/file.txt 'on * их * файловая система. Файловые объекты не полезны для передачи файлов, только информация о файлах (например, где они есть). –
Эх, может быть, вы не поняли, что я имею в виду :) Я точно узнал, что ResponseEntity не соответствует нашему намерению. Однако, согласно определению api Swagger, он генерирует код api, который возвращает ResponseEntity , а не ResponseEntity . На самом деле второй код не написан мной. Он генерируется генератором кода Swagger.: D Итак, знаете ли вы, как записать правильное определение api в первом файле? –
Niubility