angular 2 PrimeNG + spring boot文件上传错误400

时间:2017-05-11 14:07:58

标签: angular spring-boot primeng

我正在尝试将带有primeNG的文件上传到spring boot服务器端应用程序..但是我收到错误400 ..

这是我的代码: 的 app.html

<p-fileUpload name="myfile[]" url="http://localhost:8080/upload" (onUpload)="onUpload($event)" >
        <template pTemplate type="content">
            <ul *ngIf="uploadedFiles.length">
                <li *ngFor="let file of uploadedFiles">{{file.name}} - {{file.size}} bytes</li>
            </ul>
        </template>        
    </p-fileUpload>

app.ts

msgs: Message[];
  uploadedFiles: any[] = [];

    onUpload(event) {
        for(let file of event.files) {
            this.uploadedFiles.push(file);
        }

        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'File Uploaded', detail: ''});
    }

Spring启动控制器:

@RequestMapping(value="/upload",
            method=RequestMethod.POST, 
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseStatus(HttpStatus.CREATED) ResponseEntity processUpload(@RequestParam("myfile") MultipartFile file) throws IOException {

            return ResponseEntity.ok("Fichier En cours de Traitement..");
    }

CORS配置

        HttpServletResponse response = (HttpServletResponse) sRes;
        HttpServletRequest request = (HttpServletRequest) sReq;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type, Accept, X-Requested-With, Cache-Control, Accept");
        response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization");

        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            fc.doFilter(sReq, response);
        }   
    }

1 个答案:

答案 0 :(得分:1)

您应该在PrimeNG上传中使用name="myfile" - 这是您的Spring控制器所期望的名称。

<强> app.html

<p-fileUpload name="myfile" url="http://localhost:8080/upload" 
    (onUpload)="onUpload($event)" >
            <template pTemplate type="content">
                <ul *ngIf="uploadedFiles.length">
                    <li *ngFor="let file of uploadedFiles">{{file.name}} - {{file.size}} bytes</li>
                </ul>
            </template>        
        </p-fileUpload>