Java 弹簧和角度2 400(请求错误)

Java 弹簧和角度2 400(请求错误),java,spring,spring-mvc,angular,Java,Spring,Spring Mvc,Angular,我在向Spring上传文件时收到了这个400(错误请求) 上传在postman上效果很好,但在Angular2上效果不太好 这是邮递员密码。工作很好。。 我使用了基本身份验证和用户名+密码 var data = new FormData(); data.append("uploadfile", "pasta2.zip"); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("rea

我在向Spring上传文件时收到了这个400(错误请求)

上传在postman上效果很好,但在Angular2上效果不太好

这是邮递员密码。工作很好。。 我使用了基本身份验证和用户名+密码

var data = new FormData();
data.append("uploadfile", "pasta2.zip");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
 if (this.readyState === 4) {
console.log(this.responseText);
  }
 });

xhr.open("POST", "http://localhost:8080/api/uploadFile");
xhr.setRequestHeader("authorization", "Basic b3BlcmF0aW9uczpvcGVyYXRpb25z");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "59d5ebf2-6039-e924-1550-c96e491f97ee");

xhr.send(data);
这是我的Spring控制器。它简单地获取文件并将其保存到磁盘

@RestController
public class uploadFile {

private Logger logger = LoggerFactory.getLogger(this.getClass());
public String filenameZip, directoryZip;


@RequestMapping(value = "/api/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
        @ModelAttribute("uploadfile") MultipartFile uploadfile) {




    try {
        // Get the filename and build the local file path (be sure that the
        // application have write permissions on such directory)
        String filename = uploadfile.getOriginalFilename();
        String directory = "C://Develop//files";
        String filepath = Paths.get(directory, filename).toString();

        filenameZip = "c:/Develop/files/"+filename;
        directoryZip = "c:/Develop/files";

        // Save the file locally
        BufferedOutputStream stream =
                new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        stream.write(uploadfile.getBytes());
        stream.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
        unzip(filenameZip, directoryZip);
        return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

我相信这不是随请求一起发送zip文件。

因为你可以通过邮递员完成你想要的,我可以放心地假设你的问题不在后端。 问题是您没有在请求的前端(代码的角度部分)附加任何多部分文件

操纵XHR请求是实现这一点的一种粗略方法,而且自从Angular最终发布以来,您不需要这样做

一个好方法是创建一个专用服务来执行文件上载:

import { Injectable } from '@angular/core';

import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UploadService {

    //Import your APIs endpoint
    private url = AppSettings.API_ENDPOINT;

    constructor(private http:Http) { }

    upload(files:FileList){

        var formData = new FormData();


        if(files.length > 0){

            for(var i = 0; i < files.length; i++){
                formData.append("uploadfile", files[i]);
            }
            return this.http
                .post(this.url + '/api/upload', formData)
        }

    }
}

邮递员日志上写的是什么?对不起。你所说的邮递员日志是什么意思?“这是邮递员代码。工作正常”此代码不上传文件。此外,在Spring代码中,
@modeldattribute(“uploadfile”)
应该是
@RequestParam(“uploadfile”)
。角度代码使用
uploads[]
而不是
uploadFiles
。选择一个。
2016-11-27 19:14:57.862  INFO 3596 --- [io-8080-exec-10] o.e.ws.service.AccountServiceBean        : > findByUsername
2016-11-27 19:14:57.875  INFO 3596 --- [io-8080-exec-10] o.e.ws.service.AccountServiceBean        : < findByUsername
2016-11-27 19:14:57.986  INFO 3596 --- [io-8080-exec-10] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=Sun Nov 27         
19:14:57 UTC 2016, principal=operations, type=AUTHENTICATION_SUCCESS, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null}]
null
2016-11-27 19:16:12.762  INFO 3596 --- [nio-8080-exec-1] o.e.ws.service.AccountServiceBean        : > findByUsername
2016-11-27 19:16:12.851  INFO 3596 --- [nio-8080-exec-1] o.e.ws.service.AccountServiceBean        : < findByUsername
2016-11-27 19:16:12.965  INFO 3596 --- [nio-8080-exec-1] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=Sun Nov 27     
19:16:12 UTC 2016, principal=operations, type=AUTHENTICATION_SUCCESS, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null}]
Unzipping to c:\Develop\files\pasta2\dsa.txt
zone.js:1382 POST http://localhost:8080/api/uploadFile 400 (Bad Request)
import { Injectable } from '@angular/core';

import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UploadService {

    //Import your APIs endpoint
    private url = AppSettings.API_ENDPOINT;

    constructor(private http:Http) { }

    upload(files:FileList){

        var formData = new FormData();


        if(files.length > 0){

            for(var i = 0; i < files.length; i++){
                formData.append("uploadfile", files[i]);
            }
            return this.http
                .post(this.url + '/api/upload', formData)
        }

    }
}
uploadDocs($event:any){
    console.log("IMPORT")

    var files:any = $event.target.files;
    console.log(files);

    this.uploadService.uploadLibraries(files)
            .subscribe(data => this.successImport(data),
            error => this.failImport(error));
}