IONIC HTTP发布多部分/表单数据-图像上传以及JSON

时间:2018-07-16 18:28:22

标签: spring image http ionic2 multipartform-data

我正在尝试通过HTTP Post分段上传图像以及表单数据。当我尝试使用邮递员时,我可以上载,但是当我尝试将文件和表单数据作为多部分请求上载时,可以使用前端,但是出现错误的请求错误。非常感谢您的投入。已经为此工作了2天。

我的后端是Spring: 后端代码:

  @RequestMapping(value = "/lender/signup", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces =MediaType.APPLICATION_JSON_VALUE)

   @ResponseStatus(HttpStatus.CREATED)

    Object signUpLender(@RequestPart("file") MultipartFile file, 

    @RequestPart("lender") LenderInfo lenderRequest) throws Exception {

    log.info("SignUp Received, preparing to process lender")
    lenderRequest.base64Logo = mediaService.getBase64Media(file)
    Optional<Object> lenderInfo = Service.signUpLender(lenderRequest)
    log.info("Fetched LenderInfo: ${lenderInfo.get()}")
    lenderInfo.get()
}

Frontend :: Ionic:

 uploadImage() {
    // Destination URL
    var url = LENDER_URL;

    // File for Upload
    var targetPath = this.pathForImage(this.correctPath);

    // File name only
    var filename = this.correctPath;
      //const filetransfer: TransferObject = this.transfer.create();
    var options = {
        fileKey: "file",
        fileName: this.currentName,
        chunkedMode: false,
        mimeType: "multipart/form-data",
        params: {'lender':this.userData,
            'file':this.currentName},
        httpMethod:'POST'
    };
      let headers = new HttpHeaders();
      headers.append('Content-Type', undefined);
      headers.append('Access-Control-Allow-Origin', '*');
      headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS,PUT');
        this.formData.then((_)=>{
            this.loading = this.loadingCtrl.create({
                content: 'Uploading...',
            });
            this.loading.present();
            this.network.postService(url,options,headers).then(()=>{
                this.loading.dismissAll();
                this.presentToast('Image succesful uploaded.');
            }, err => {
                this.loading.dismissAll();
                console.log(JSON.stringify(err));
                this.presentToast('Error while uploading file.');
            });
        },err=>{JSON.stringify(err)});

在邮递员中,当我尝试命中端点时,我可以发布值,因为我选择了图像(文件)和JSON作为文件。请让我知道您的输入。

谢谢

1 个答案:

答案 0 :(得分:0)

我已经经历过,解决它的一种方法是指定类型@RequestPart(value =“ nameOfResource”并消耗= {“ multipart / form-data”}

不要忘记在Ionic中指定Content的名称。希望对您有所帮助。

这是下面的Java示例:

RequestMapping(value = "/add", method = RequestMethod.POST, consumes = {"multipart/form-data"}, produces = "application/json")
        public ResponseEntity<?> add(@RequestPart(value = "image", required = true) MultipartFile image, 
                                     @RequestPart(value = "team", required = true) @Valid Team team, BindingResult bResult) {

}