Проблемы с axios, Spring boot и base64 - PullRequest
       12

Проблемы с axios, Spring boot и base64

0 голосов
/ 20 декабря 2018

Я пытаюсь сделать сообщение из своего собственного приложения реагирования на приложение Spring Boot, но получаю эту ошибку:

java.lang.IllegalArgumentException: недопустимый символ base64 a

Реагирует на собственный код:

axios({
    method: 'post',
    url: 'myip',
    data: {
      teste: photo.image.base64,
    },
    headers: {'content-type': 'application/json'},
  }) 
  .then(function (response) {
    console.log("works");
  })
  .catch(function (error) {
    console.log(error);
  });

Spring Boot Code

@RequestMapping(value = "/", method = RequestMethod.POST)
public Map<String, String> upload (@RequestBody Map<String, String> payload) {
    byte[] imageByte;
    String encodedString = payload.get("teste");
    String fileName = (new Date()).toString();
    fileName = fileName.replace(' ', '_');
    fileName = fileName.replace(':', '_');

    try {
        imageByte = Base64.getDecoder().decode(encodedString.toString());
        FileUtils.writeByteArrayToFile(new File(fileName + ".png"), imageByte);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("error");
    }
    return response;
}

Редактировать: Stacktrace -

 java.lang.IllegalArgumentException: Illegal base64 character a
        at java.util.Base64$Decoder.decode0(Unknown Source)
        at java.util.Base64$Decoder.decode(Unknown Source)
        at java.util.Base64$Decoder.decode(Unknown Source)
        at com.pac.upload.UploadController.login(UploadController.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

Я не вижу, что я 'м отсутствует.Кто-нибудь может мне помочь?Заранее спасибо!

1 Ответ

0 голосов
/ 26 июля 2019

Вот мой пример загрузки изображения от реакции с Axios.

Сервер:

@PostMapping("/{businessId}/gallery")
    public Object singleImageUpload(@RequestParam("newImage") MultipartFile file) {
        if (file.isEmpty()) {
            return new GeneralResponse(ErrorsEnum.INVALID_IMAGE);
        }
        try {
            Business business = getUserBusinessLogged();
            byte[] bytes = file.getBytes();

            ...

            return new GeneralResponse(ErrorsEnum.OK);
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error saving file", e);
            return new GeneralResponse(ErrorsEnum.SAVE_FAILED, "Problems saving file.");
        } catch (ControlledException ex) {
            return new GeneralResponse(ErrorsEnum.SAVE_FAILED, ex.getMessage());
        }
    }

Клиент Axios:

const postGalleryImageRequest = async (sessionToken, businessId, image) => {
    const data = new FormData();
    data.append('newImage', image);
    const result = await api.post('business/' + businessId + '/gallery', data, {
        headers: { 
            Authorization: sessionToken,
            'Content-Type': 'multipart/form-data',
        }
    })  .then((response) => {
            return response.data
        })
        .catch(error => {
             ....
        })
    return result;
}

Настройка Axios:

import axios from 'axios';

export const baseUrl = 'https://host:port/api/';

export default
   axios.create({
      baseURL: baseUrl,
      timeout: 30000
   });
...