POST request with multipart / form-data header with angle 4

0

When trying to make a request POST to the server with angle 4, returns error, I have already tried a million things and nothing, I have investigated and nothing.

this.http.post('localhost:53286/api/Home/Signup', formData, options).suscribe(
           res>=>{}
           err=>{}
)

That's my method to do the post to the server

 let options : RequestOptionsArgs = new RequestOptions();  
 options.header.append({'Content-Type':'multipart/form-data'});

When making the request, it returns error 500, I've been with this error for days, maybe it affects the way I upload the file and it's this way. having @ViewChild('fileInput') FileInput;

Upload(){
     let FileBrowser = this.FileInput.NativeElement;
     if(FileBrowser.files && FileBrowser.files[0])
       this.signupmodel.CIPath = FileBrowser.files[0];
  }

Being the signupmodel.CIPath where the image address is stored.

    
asked by Jhondavid17 19.12.2017 в 22:13
source

1 answer

0

To upload files with Angular, it is best to use the XHR instead of the HTTP service of Angular 2/4 since it does not go very well in this aspect ...

I have prepared a function in TypeScript to use XHR comfortably:

export const xhr = (
    method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' = 'GET',
    url: string,
    headers: { [key: string]: any },
    body = null,
    files: File[] = []
): Promise<any> => {
    return new Promise((resolve, reject) => {
        const formData: FormData = new FormData();
        const params = body !== null ? body : {};
        for (let i = 0; i < files.length; i++) {
            formData.append('files[]', files[i], files[i].name);
        }
        Object.keys(params).forEach(key => formData.append(key, params[key]));
        const req = new XMLHttpRequest();
        req.onreadystatechange = () => {
            if (req.readyState === 4) {
                if (req.status >= 200 && req.status <= 299) {
                    resolve(JSON.parse(req.response));
                } else {
                    reject(req.response);
                }
            }
        };
        req.onerror = () => reject(null);
        req.onabort = () => reject(null);
        req.open(method, url, true);
        Object.keys(headers).forEach(key => req.setRequestHeader(key, headers[key]));
        req.send(formData);
    });
};

Example of use:

const file = ...; // Tu fichero
xhr('POST', '${env.baseUrl}/upload/file', {
            'Authorization': this.authService.bearerToken(),
            'Accept': 'application/json' }, { name, date }, [file])
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

If you continue to have the error 500, what is the Server, it is no longer because you send the data wrong, but because it treats you badly on your server.

    
answered by 26.12.2017 в 23:45