reactjs - React原生上传图片 Spring boot

标签 reactjs spring spring-boot upload native

我正在尝试将图像从 React Native 应用程序上传到 Java Spring Boot 服务器,但无法使其工作。

应用程序在 Chrome 控制台中的请求是:

userimage FormData {_parts: Array(1)}_parts: Array(1)0: Array(2)0: "photo"1: name: "file_photo"uri: "content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F47/ORIGINAL/NONE/226557028"__proto__: Objectlength: 2__proto__: Array(0)length: 1__proto__: Array(0)__proto__: Object

后端的错误是:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found] with root cause

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Spring boot controller:
@PostMapping(value = "/signup", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> signupUser(@RequestParam("photo") MultipartFile photo) {
...
}

React native code:
openImagePicker = () => {
    ImagePicker.showImagePicker(this.options, async response => {
      this.setState({originUri: response.uri})
      const file = new FormData();
      file.append('photo', {
          uri: this.state.originUri,
          name: 'file_photo'
      });
      console.log('photo before resize: ', file)
      //here i call the register function(file)
}

function register(userImage) {

  console.log('photo from register api: ', file)

  return axios({ method: 'post', 
                baseURL: constants.BASE_URL,
                url: '/api/auth/signup',
                 headers: {
                   'Content-Type': 'multipart/form-data'
                 },
                data: userImage,
               })
        .then(res => {
          return res.data
         } ) 
        .catch( error => {
          console.log('error request api: ', error)

        });
}

最佳答案

我已经成功修复了这个问题:

react native :

--来自图像上传组件

openImagePicker = () => {
    ImagePicker.showImagePicker(this.options, async response => {
      this.setState({originUri: response.uri})
      let timestamp = +new Date;
      let fileName = timestamp + '_' + response.fileName;
      if (response.didCancel) {
          console.log('User cancelled image picker')
          return
      } else if (response.error) {
          console.log('ImagePicker Error: ', response.error)
          return
      } else if (response.customButton) {
          console.log('User tapped custom button: ', response.customButton)
          return
      } else {
          const source = { uri: response.uri };
          this.setState({
            avatarSource: source,
          });
      }


      let { height, width, quality, format, avatarSource } = this.state

      // Resize and post the thumb 
      const resizedImageUri = await ImageResizer.createResizedImage(
          this.state.originUri,
          this.state.height,
          this.state.width,
          this.state.format,
          this.state.quality
      ).then(({uri}) => {
        let imageProperties = {
          uri: uri,
          name: fileName,
          type: 'image/png',
        }
        this.props.onUpload(imageProperties);
      })
    })
  }

-- API 调用注册

export function register(name, username, email, password, imageProperties) {
  let formDataPayload = new FormData();
  //IMPORTANT !!!!! this picture element form needs 3 parameters !!!!! : URL, NAME and TYPE
  formDataPayload.append('photo', {
    uri: imageProperties.uri,
    name: imageProperties.name,
    type: 'image/png',
  });
  formDataPayload.append('name', name);
  formDataPayload.append('username', username);
  formDataPayload.append('email', email);
  formDataPayload.append('password', password);
  return request({method: 'post', 
                  url: '/api/auth/signup/',
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  },
                  data: formDataPayload
                  })
}

JAVA Spring 启动:

@PostMapping(value = "/api/auth/signup/")
    public ResponseEntity<?> signupUser(HttpServletRequest request,
                                          @RequestParam("photo") MultipartFile photo,
                                          @RequestParam("name") String name,
                                          @RequestParam("username") String username,
                                          @RequestParam("email") String email,
                                          @RequestParam("password") String password,
                                        ) throws IOException {

关于reactjs - React原生上传图片 Spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58336317/

相关文章:

spring - 在spring配置文件中设置资源

html - React useEffect 保存文本区域文本

javascript - 获取上传文件的大小 React JS

java - Spring静态资源映射: controller vs addResourceHandler

java - Spring Boot - 基于其他属性自动配置属性?

spring-boot - 具有多个安全配置的 Spring Security 6 配置

java - Spring-Boot JPA - 使用 JSON RequestBody 中的外键插入数据库会导致空对象

javascript - 无法导入 typescript react 模态

javascript - React - 组件导出多个组件

spring - Spring JpaRepository 自定义实现是否自动进行事务处理?