FileSystemResource в MultipartFile - PullRequest
       27

FileSystemResource в MultipartFile

0 голосов
/ 15 февраля 2020

Я хочу отправить свое изображение из своего хранилища, используя следующий путь:

MultiValueMap<String, Object> image = new LinkedMultiValueMap<String, Object>(); 
image.add("image", new FileSystemResource("C:\\xx\\xx\\xx\\xx\\xx\\xx\\xx\\img\\xx.jpg"));

, поэтому я вызываю объект, используя следующий код:

MultiValueMap<String, Object> body = new LinkedMultiValueMap<String,Object>();
body.add("image", image);

Затем я получаю эта ошибка:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class sun.nio.ch.ChannelInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])

Я использую Шаблон Rest пружинной загрузки, который требует, чтобы я отправил методом POST объект MultipartFile. Теперь я не знаю, как преобразовать в тип MultipartFile,
, чтобы шаблон отдыха мог принять мой запрос.

Примечание. Я хочу использовать body.add("image", image.getResource());, но он не отображается в выборе, поскольку изображение не было типа MultipartFile.

1 Ответ

0 голосов
/ 15 февраля 2020

Это сработало для меня.

    @GetMapping(path = "/copy", produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<String> copyFile() {

        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        body.add("image", new FileSystemResource("test.jpg"));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);

        String serverUrl = "http://localhost:8080/upload";

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate
                .postForEntity(serverUrl, requestEntity, String.class);

        return response;
    }

    @PostMapping(path = "/upload", produces = MediaType.TEXT_PLAIN_VALUE)
    public String uploadFile(@RequestParam("image") MultipartFile file) {

        try {

            byte[] bytes = file.getBytes();
            Path path = Paths.get("./uploadedImages/" + file.getOriginalFilename());
            Files.write(path, bytes);

        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }

        return "File Uploaded";
    }
...