Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Getting FileUploadException:请求被拒绝,因为从Angular 2发布文件时在控制器中找不到多部分边界_Angular_Spring Mvc_Angular2 Forms_Http Request Parameters_Angular File Upload - Fatal编程技术网

Getting FileUploadException:请求被拒绝,因为从Angular 2发布文件时在控制器中找不到多部分边界

Getting FileUploadException:请求被拒绝,因为从Angular 2发布文件时在控制器中找不到多部分边界,angular,spring-mvc,angular2-forms,http-request-parameters,angular-file-upload,Angular,Spring Mvc,Angular2 Forms,Http Request Parameters,Angular File Upload,我的控制器方法如下: @RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json") public void saveUpdate(@RequestPart("org") Organization org, @RequestPart("logo") MultipartFile file){ LOG.info("

我的控制器方法如下:

     @RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json")
     public void saveUpdate(@RequestPart("org") Organization org, @RequestPart("logo") MultipartFile file){

     LOG.info("ORG :"+org != null ? org.getName()+"  : " + file : null);

     }
在我发送的表格中,如下所示:

  public saveUpdateOrganization(organization: Organization, file: File): Observable<void> {
      let headers = new Headers({ 'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*' });
      let options = new RequestOptions({headers: headers});
      let formData = new FormData();
      formData.append("logo",file);
      formData.append("org", new Blob([JSON.stringify(organization)],
      {
        type: "application/json"
      }));
      return this.http.post(AppSettings.API_ENDPOINT + "org", organization, options).map((response) => {
        return;
      })
  }
public saveUpdateOrganization(组织:组织,文件:文件):可观察{
let headers=新的头({'Content Type':'multipart/form data','Access Control Allow Origin':'*');
let options=newrequestoptions({headers:headers});
设formData=new formData();
formData.append(“logo”,文件);
formData.append(“org”,新Blob([JSON.stringify(organization)],
{
类型:“application/json”
}));
返回this.http.post(AppSettings.API_ENDPOINT+“org”、组织、选项).map((响应)=>{
返回;
})
}
问题在哪里?需要纠正的地方


请提出建议。

我通过以下方式解决了此问题:

我们需要在XMLHttpRequest中设置请求主体

      Observable.fromPromise(new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();

        // setting the params 
        formData.append("logo",file);
        formData.append("org", new Blob([JSON.stringify(organization)],
        {
            type: "application/json"
        }));

        // call post API method
        xhr.open("POST", API_URL , true);
        xhr.send(formData)
        }));

如果有任何其他智能方式,请随时提出建议。

因为您对使用XHR很熟悉,这里有一个更高级的实现,带有上传中止和进度计数器。我们使用的不是
承诺
,而是
可观察的

uploadFile(url: string, file: File, metadata?: any): Observable<string | number> {

    // Initiates a FormData object to be sent to the server
    const fd: FormData = new FormData()

    fd.append('file', file)

    // In case you want to add other fields to the `FormData`
    if (metadata) {

        for (const key in metadata) {

            if (metadata.hasOwnProperty(key)) {

                fd.append(key, metadata[key])
            }
        }
    }

    const xhr = new XMLHttpRequest

    return Observable.create(observer => {

        // Count progress of upload
        xhr.upload.onprogress = (progress) => {

            let percentCompleted

            if (progress.lengthComputable) {

                percentCompleted = Math.round(progress.loaded / progress.total * 100)

                if (percentCompleted < 1) {

                    observer.next(0)

                } else {

                    observer.next(percentCompleted)
                }
            }
        }

        xhr.onload = (e) => {

            if (e.target['status'] !== 200) {

                observer.error(e.target['responseText'])

            } else {

                observer.next(e.target['responseText'])

                observer.complete()
            }
        }

        xhr.onerror = () => {

            observer.error('Upload error')
        }

        xhr.onabort = () => {

            observer.error('Transfer aborted by the user')
        }

        xhr.open('POST', API_DOMAIN + url)

        xhr.setRequestHeader('Authorization', `Bearer ${someAuthToken}`)

        // Send the FormData
        xhr.send(fd)

        // Allows to abort file transfer on unsubscription
        // sub.unsubscribe() <- will abort upload if not yet completed
        return () => xhr.abort()
    })
}

试试这个@borislemke,我正在ts服务中获取文件详细信息,但我无法将其发布到控制器。
uploadRef;

upload() {

    this.uploadRef = uploadFile('media/upload', someFileFromInputElement, {file_name: 'avatar.jpeg'}).subscribe(progress => {
        if (typeof progress === 'number') {
            console.log('upload progress', progress)
            if (progress === 100) alert('Upload complete!')
        }
    })
}

// Abort upload
cancelUpload(): void {
    if (this.uploadRef) this.uploadRef.unsubscribe()
}