Reputation: 71
How to upload image using multipart on DreamFactory?
I am using angualr2, tried xhr and http.post. Both are not working I get 201 status code and with empty resource back. Document just says
POST http://{url}/api/v2/{storage_service_name}
Request header:
...
Content-Type: multipart/form-data;
...
Request payload:
-- <file content> --
no clear explanation
Upvotes: 1
Views: 702
Reputation: 439
Been trying to figure this out too and the documentation really wasn't much help. This is what I eventually used
Created a component as below. The path input represents the folder already created on the files service. The code still needs to be refactored to create the folder if it doesn't exist, but this works so far.
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { Headers, Http } from '@angular/http';
import * as constants from '../shared/config';
@Component({
selector: 'file-upload',
template: '<input type="file" #fileInput>'
})
export class FileUploadComponent {
@Input() multiple: boolean = false;
@Input() path: string = '';
@ViewChild('fileInput') inputEl: ElementRef;
baseResourceUrl: string = constants.API_BASE_URL + '/api/v2/files/';
constructor(private http: Http) {}
upload() {
console.log("changed");
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let fileName: string = '';
console.log(inputEl.files);
let formData = new FormData();
if (fileCount > 0) { // a file was selected
formData.append('files[]', inputEl.files.item(0), inputEl.files.item(0).name);
formData.append('pmCase', '100');
fileName = inputEl.files.item(0).name;
let myHeader = new Headers();
let token = localStorage.getItem('session_token');
myHeader.append('Content-Type', 'multipart/form-data');
myHeader.append('X-Dreamfactory-API-Key', 'xxxxxxxxxxx');
myHeader.append('X-Dreamfactory-Session-Token', token);
this.http
.post(`${this.baseResourceUrl + this.path + fileName}`, formData, { headers: myHeader })
.map((resp) => resp.json())
.subscribe((uploadResp) => {
console.log(uploadResp);
}, (error) => console.error(error));
}
}
}
Upvotes: 2
Reputation: 21
You should check that the html input name for the file is "files" - Any other name for the file field will not upload content. Also, you need to post it to the directory or path that you want the file stored. Assuming the directory is already there, it should upload the file as expected. Good Luck!
Upvotes: 1