我正在尝试在Angular 2中进行文件上传。尝试
let file:FileList = inputEl.files[0];
console.log(file);
this.http.post(url, file)
.map(res => {
return res.headers.get("content-type");
})
.catch(err => {
return Observable.throw(err);
})
.subscribe((res) => { // <-- this function
console.log(res)
});
我现在可以看到POST调用。但我仍然无法看到该文件 上传发生,文件上传请求应该如何。
答案 0 :(得分:3)
您的http服务文件:
import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;
@Injectable()
export class HttpClient {
requestUrl: string;
responseData: any;
handleError: any;
constructor(private router: Router,
private http: Http,
private constants: Constants,
) {
this.http = http;
}
postWithFile (url: string, postData: any, files: File[]) {
let headers = new Headers();
let formData:FormData = new FormData();
formData.append('files', files[0], files[0].name);
// For multiple files
// for (let i = 0; i < files.length; i++) {
// formData.append(`files[]`, files[i], files[i].name);
// }
if(postData !=="" && postData !== undefined && postData !==null){
for (var property in postData) {
if (postData.hasOwnProperty(property)) {
formData.append(property, postData[property]);
}
}
}
var returnReponse = new Promise((resolve, reject) => {
this.http.post(this.constants.root_dir + url, formData, {
headers: headers
}).subscribe(
res => {
this.responseData = res.json();
resolve(this.responseData);
},
error => {
this.router.navigate(['/login']);
reject(error);
}
);
});
return returnReponse;
}
}
调用您的函数(组件文件):
onChange(event) {
let file = event.srcElement.files;
let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
console.log(result);
});
}
您的HTML代码:
<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">
您的服务器文件(与PHP一样):
print_r($_FILES);
答案 1 :(得分:1)
只有在订阅时才会发送Http请求。
this._http.post("url", "file")
.map(res => {
return res.headers.get("content-type");
})
.catch(err => {
return Observable.throw(err);
})
.subscribe((res) => { // <-- this function
console.log(res)
})
您可以找到有关使用Angular 2 here创建http客户端的更多信息。
答案 2 :(得分:0)
1. remember when you are submitting form data with file , header should be blanked
let headers = new Headers();
let options = new RequestOptions({ headers: headers });
2. Rest You can follow from upper example @Bharat Chauhan
3. i tested with all others headers , but it worked if its leave blanked !
Step 1. <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
Step 2.
fileChangeEvent(e:any):void{
let commentOperation:Observable<any>;
let fileList: FileList = e.target.files;
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('file', file, file.name);
commentOperation = this.test1Service_.submitComment( formData);
commentOperation.subscribe(
fileUpload => {
console.log(fileUpload)
},
err => {
// Log errors if any
console.log(err);
}
);
}
Step 3:
submitComment (body: any): Observable<any> {
let headers = new Headers();
let options = new RequestOptions({ headers: headers });
return this.http.post(this.commentsUrl,body , options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
Step 4: PHP :
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(array('status' => false));
exit;
}
$path = 'uploads/';
if (isset($_FILES['file'])) {
$originalName = $_FILES['file']['name'];
$ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = md5($_FILES['file']['tmp_name']).$ext;
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
}
else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
答案 3 :(得分:0)
fileChange(event){
let fileList: FileList = event.srcElement.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('enctype', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
我参考了:File Upload In Angular 2? 但在改变内容类型&#39;到&#39; enctype&#39;和&#39; event.target.files&#39;到&#39; event.srcElement.files&#39;