需要的部分“文件”不存在 - Angular2发布请求 [英] Required request part 'file' is not present - Angular2 Post request

查看:2330
本文介绍了需要的部分“文件”不存在 - Angular2发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Angular2和SpringBoot来完成我的文件上传功能。我可以证明,我的文件上传的Java代码工作正常,因为我已经使用邮递员成功地进行了测试。

然而,当从Angular2前端发送文件,我得到的HTTP 400响应说所需的请求部分'文件'不存在



这是如何

  savePhoto(photoToSave:File){

let formData: FormData = new FormData();
formData.append('file',photoToSave);

//这将用于使用自定义请求选项
this._globals.setRequestFrom(save-photo);


savePath = this._http
.post(this._endpointUrl +save-photo,formData)
.map(
res = > {
return res.json();
}

.catch(handleError);

return savedPath;




注意我写了一个 CustomRequestOptions 类,它扩展了 BaseRequestOptions 以追加授权标头和内容类型标头。内容类型标题将有条件地添加。



以下是代码。

  @Injectable() 
export class CustomRequestOptions extends BaseRequestOptions {
constructor(private _globals:Globals){
super();

this.headers.set('X-Requested-By','Angular 2');
this.headers.append('virglk',vigamage);


merge(options?:RequestOptionsArgs):RequestOptions {

var newOptions = super.merge(options);

让hdr = this._globals.getAuthorization();
newOptions.headers.set(Authorization,hdr);如果(this._globals.getRequestFrom()!=save-photo){
newOptions.headers.set('Content-Type','application / json');

if
} else {
//来自保存照片的请求
console.log(来自保存照片的请求);
}

return newOptions;







这个条件头附加功能正常工作。这样做的目的是为每个请求添加'Content-Type','application / json'头部,Spring控制器中的文件上传方法将不会接受它。 (返回http 415)



一切似乎都很好。但是我得到所需的请求部分'文件'不存在错误响应。这是为什么?我将这个参数添加到Data表单中。

  let formData:FormData = new FormData(); 
formData.append('file',photoToSave);

这是Spring Controller方法供您参考。

  @RequestMapping(method = RequestMethod.POST,value =/ tender / save-new / save-photo,consumes = {multipart / form-data})
public ResponseEntity<?> uploadPhoto(@RequestParam(file)MultipartFile文件){

if(file.isEmpty()){
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(DEBUG:附加文件为空);
返回新的ResponseEntity< ErrorResponse>(errorResponse,HttpStatus.NOT_FOUND);
}
字符串returnPath = null;
try {
//上传东西
} catch(IOException e){
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(e.getMessage());
返回新的ResponseEntity< ErrorResponse> (errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
}

返回新的ResponseEntity< String>(returnPath,HttpStatus.OK);

$ / code>

编辑 - 添加捕获的请求的有效载荷通过浏览器





正如你所看到的,试试添加





$ b

解决方案

pre $ {
'Content-Type':'multipart / form-data'
},
pre

到您的

  .post(this._endpointUrl + save-photo,formData)


I am trying to get my file upload functionality done using Angular2 and SpringBoot. I can certify that my java code for the file uploading working fine since I have tested it successfully using Postman.

However, when it comes to sending the file from Angular2 front end, I am getting the HTTP 400 response saying Required request part 'file' is not present.

This is how I send the POST request from Angular2.

savePhoto(photoToSave: File) {

    let formData: FormData = new FormData();
    formData.append('file', photoToSave);

    // this will be used to add headers to the requests conditionally later using Custom Request Options
    this._globals.setRequestFrom("save-photo");


    let savedPath = this._http
        .post(this._endpointUrl + "save-photo", formData)
        .map(
        res => {
            return res.json();
        }
        )
        .catch(handleError);

    return savedPath;

}

Note that I have written a CustomRequestOptions class which extends BaseRequestOptions in order to append Authorization header and Content Type header. Content Type header will be added conditionally.

Following is the code for that.

@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
    constructor(private _globals: Globals) {
        super();

        this.headers.set('X-Requested-By', 'Angular 2');
        this.headers.append('virglk', "vigamage");
    }

    merge(options?: RequestOptionsArgs): RequestOptions {

        var newOptions = super.merge(options);

        let hdr = this._globals.getAuthorization();
        newOptions.headers.set("Authorization", hdr);

        if(this._globals.getRequestFrom() != "save-photo"){
            newOptions.headers.set('Content-Type', 'application/json');
        }else{
            //request coming from save photo
            console.log("request coming from save photo");
        }

        return newOptions;
    }

}

This conditional header appending is working fine. The purpose of doing that is if I add 'Content-Type', 'application/json' header to every request, file upload method in Spring controller will not accept it. (Returns http 415)

Everything seems to be fine. But I get Required request part 'file' is not present error response. Why is that? I am adding that param to the form Data.

let formData: FormData = new FormData();
formData.append('file', photoToSave);

This is the Spring Controller method for your reference.

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo", consumes = {"multipart/form-data"})
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){

    if (file.isEmpty()) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage("DEBUG: Attached file is empty");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
    }
    String returnPath = null;
    try {
        // upload stuff
    } catch (IOException e) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(e.getMessage());
        return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}

EDIT - Adding the payload of the request captured by the browser

As you can see, the param "file" is available there.

解决方案

Try to add

headers: {
            'Content-Type': 'multipart/form-data'
        },

to your

.post(this._endpointUrl + "save-photo", formData)

这篇关于需要的部分“文件”不存在 - Angular2发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆