向Springboot API的角度上传文件失败,并显示错误:当前请求不是多部分请求

问题描述

文件从Angular应用程序上传到springboot API失败,并显示错误

org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause
org.springframework.web.multipart.MultipartException: Current request is not a multipart request

我认为问题在于请求的Content-Type设置为application / json。我无法设置上载请求的Content-Type,因为我正在使用的Angular Interceptor覆盖了该请求。 是否有办法仅针对少量请求更新标头中的内容类型。 当我从标题删除内容类型时,文件上传有效,但其他功能创建,删除和更新均无效。

HttpInterceptor:

@Injectable({
    providedIn: 'root'
})
export class AuthenticationInterceptorService implements HttpInterceptor {

    constructor(private authenticationService: AuthenticationService) {
    }

    intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.authenticationService.isUserLoggedIn()) {
            const authReq = req.clone({
                headers: new HttpHeaders({
                    Authorization: `Bearer ${sessionStorage.getItem('sessionToken')}`,'Content-Type': 'application/json'
                })
            });
            return next.handle(authReq);
        }
        else {
            return next.handle(req);
        }
    }
}

UploadService:

upload(scriptId: string,file: File): Observable<HttpEvent<any>> {
        const formData = new FormData();
        formData.append('file',file);
        const request = new HttpRequest('POST',`${this.serviceUrl}/upload?s=${scriptId}`,formData,{
            reportProgress: true,responseType: 'json'
        });
        return this.httpClient.request(request);
    }

Springboot上传控制器:

@PostMapping(value = "upload")
    public ResponseEntity uploadScript(@RequestParam String s,@RequestPart multipartfile file) {
        Script script = scriptService.findByScriptId(s);
        if (fileUploadService.save(file,script.getLocation())) {
            return ResponseEntity.status(HttpStatus.OK).body(new Response(1,"File uploaded successfully.",false));
        }
        else {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(new Response(0,"Unable to upload file,try again later.",false));
        }
    }

请求

Accept: application/json,text/plain,*/*
Accept-Encoding: gzip,deflate,br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Authorization: Bearer <token>
Connection: keep-alive
Content-Length: 868175
Content-Type: application/json
Host: localhost:8888
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/85.0.4183.102 Safari/537.36
s: 2B03BA9F0A0D5ED680000175A1FF27DC
------WebKitFormBoundaryxIVck8AqW8Dnd9xp
Content-disposition: form-data; name="file"; filename="sample.pdf"
Content-Type: application/pdf


------WebKitFormBoundaryxIVck8AqW8Dnd9xp--

UploadFile HTML

<form class="form-horizontal" id="uploadFileForm" [formGroup]="uploadFileForm" (ngSubmit)="uploadFile()" enctype="multipart/form-data">
    <mat-dialog-content>
        <div *ngIf="message" class="alert {{messageClass}}" role="alert">{{ message }}</div>
        <section class="form-section">
            <div class="custom-file">
                <input type="file" class="custom-file-input" id="file" name="file" formControlName="file" accept="*/*" (change)="onFileChange($event.target.files)" [ngClass]="{ 'is-invalid': submitted && f.file.errors }" autocomplete="off">
                <label class="custom-file-label" #fileLabel for="file">Choose file</label>
                <mat-error *ngIf="submitted && f.file.errors">
                    <div *ngIf="f.file.hasError('required')">File is required</div>
                </mat-error>
            </div>
        </section>
        <section class="form-full-width">
            <div *ngIf="currentFile" class="progress">
                <div class="progress-bar" role="progressbar" attr.aria-valueNow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" [ngStyle]="{ width: progress + '%' }">
                    {{ progress }}%
                </div>
            </div>
        </section>
    </mat-dialog-content>
    <mat-dialog-actions align="end">
        <button id="cancelBtn" name="cancelBtn" mat-button mat-dialog-close>Cancel</button>
        <button type="submit" id="submitBtn" name="submitBtn" mat-flat-button color="primary">Submit</button>
    </mat-dialog-actions>
</form>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)