我知道这是一个非常普遍的问题,但我不能上传角2.文件我曾尝试
1)http://valor-software.com/ng2-file-upload/和
2)http://ng2-uploader.com/home
......但失败了。有没有人上传的角度文件?你用什么方法?怎么办呢?如果提供任何示例代码或演示链接将非常感激。
角2提供了上传文件的良好支持。没有第三方库需要。
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
let fileList: FileList = event.target.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();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append('Content-Type', '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)
)
}
}
使用@角/芯“: ”〜2.0.0“ 和@角/ HTTP: ”〜2.0.0“
今天,我被整合ng2-file-upload包到我的角6的应用程序,这是非常简单的,请找到下面的高级代码。
导入NG2文件上传模块
app.module.ts
import { FileUploadModule } from 'ng2-file-upload';
------
------
imports: [ FileUploadModule ],
------
------
组件TS文件导入FileUploader
app.component.ts
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
------
------
const URL = 'http://localhost:3000/fileupload/';
------
------
public uploader: FileUploader = new FileUploader({
url: URL,
disableMultipart : false,
autoUpload: true,
method: 'post',
itemAlias: 'attachment'
});
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
}
------
------
组件的HTML文件中添加标签
app.component.html
<input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
在线工作stackblitz链接:https://ng2-file-upload-example.stackblitz.io
Stackblitz代码示例:https://stackblitz.com/edit/ng2-file-upload-example
尽量不要设置options
参数
this.http.post(${this.apiEndPoint}, formData)
并确保你没有设置globalHeaders
在你的Http工厂。
在最简单的形式,下面的代码在角6/7
this.http.post("http://destinationurl.com/endpoint", fileFormData)
.subscribe(response => {
//handle response
}, err => {
//handle error
});
我一直在使用的参考上传文件。没有包需要上传的文件这样。
//代码写在.TS文件
@ViewChild("fileInput") fileInput;
addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
this.admin.addQuestionApi(fileToUpload)
.subscribe(
success => {
this.loading = false;
this.flashMessagesService.show('Uploaded successfully', {
classes: ['alert', 'alert-success'],
timeout: 1000,
});
},
error => {
this.loading = false;
if(error.statusCode==401) this.router.navigate(['']);
else
this.flashMessagesService.show(error.message, {
classes: ['alert', 'alert-danger'],
timeout: 1000,
});
});
}
}
//代码写在service.ts文件
addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);
return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
.map(response => response.json())
.catch(this.errorHandler);
}
//代码写在HTML
<input type="file" #fileInput>
从上面的答案我建立这个与角5.x的
只需拨打uploadFile(url, file).subscribe()
触发上传
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";
@Injectable()
export class UploadService {
constructor(private http: HttpClient) { }
// file from event.target.files[0]
uploadFile(url: string, file: File): Observable<HttpEvent<any>> {
let formData = new FormData();
formData.append('upload', file);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', url, formData, options);
return this.http.request(req);
}
}
使用它像这样在你的组件
// At the drag drop area
// (drop)="onDropFile($event)"
onDropFile(event: DragEvent) {
event.preventDefault();
this.uploadFile(event.dataTransfer.files);
}
// At the drag drop area
// (dragover)="onDragOverFile($event)"
onDragOverFile(event) {
event.stopPropagation();
event.preventDefault();
}
// At the file input element
// (change)="selectFile($event)"
selectFile(event) {
this.uploadFile(event.target.files);
}
uploadFile(files: FileList) {
if (files.length == 0) {
console.log("No file selected!");
return
}
let file: File = files[0];
this.upload.uploadFile(this.appCfg.baseUrl + "/api/flash/upload", file)
.subscribe(
event => {
if (event.type == HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% loaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely loaded!');
}
},
(err) => {
console.log("Upload Error:", err);
}, () => {
console.log("Upload done");
}
)
}
由于@Eswar。此代码工作完美的我。我想某些事情到解决方案:
我得到的错误:java.io.IOException: RESTEASY007550: Unable to get boundary for multipart
为了解决这个错误,你应该删除“内容类型”,“多/表单数据”。它解决了我的问题。
由于代码示例是有点过时,我想我会分享一个最近的一种方法,采用了棱角分明4.3和新(ER)HttpClient的API,角@ /普通/ HTTP
export class FileUpload {
@ViewChild('selectedFile') selectedFileEl;
uploadFile() {
let params = new HttpParams();
let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])
const options = {
headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
params: params,
reportProgress: true,
withCredentials: true,
}
this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
data => {
console.log("Subscribe data", data);
},
(err: HttpErrorResponse) => {
console.log(err.message, JSON.parse(err.error).error.message);
}
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}
在角2+,其离开的Content-Type空是非常重要的。如果你设定了“的Content-Type”到“多/表单数据”上传都不行!
upload.component.html
<input type="file" (change)="fileChange($event)" name="file" />
upload.component.ts
export class UploadComponent implements OnInit {
constructor(public http: Http) {}
fileChange(event): void {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file = fileList[0];
const formData = new FormData();
formData.append('file', file, file.name);
const headers = new Headers();
// It is very important to leave the Content-Type empty
// do not use headers.append('Content-Type', 'multipart/form-data');
headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
const options = new RequestOptions({headers: headers});
this.http.post('https://api.mysite.com/uploadfile', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
);
}
}
}
我从成功吸用下面的工具。我在与primeNg游戏没有皮肤,只是通过我的建议。
这个简单的解决方案为我工作:文件upload.component.html
<div>
<input type="file" #fileInput placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
</div>
然后执行上传组件中直接使用XMLHttpRequest。
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {
@ViewChild('fileInput') fileInput;
constructor() { }
ngOnInit() {
}
private upload() {
const fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
formData.append('files', fileBrowser.files[0]);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/Data/UploadFiles', true);
xhr.onload = function () {
if (this['status'] === 200) {
const responseText = this['responseText'];
const files = JSON.parse(responseText);
//todo: emit event
} else {
//todo: error handling
}
};
xhr.send(formData);
}
}
}
如果您使用的dotnet核心,参数名称必须与字段名称匹配。文件在这种情况下:
[HttpPost("[action]")]
public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files)
{
return await _binaryService.UploadFilesAsync(files);
}
这个答案是http://blog.teamtreehouse.com/uploading-files-ajax的plagiate
编辑:上传完成后,必须清除文件上传,以便用户可以选择一个新的文件。而不是使用XMLHttpRequest的,也许这是更好地使用抓取:
private addFileInput() {
const fileInputParentNative = this.fileInputParent.nativeElement;
const oldFileInput = fileInputParentNative.querySelector('input');
const newFileInput = document.createElement('input');
newFileInput.type = 'file';
newFileInput.multiple = true;
newFileInput.name = 'fileInput';
const uploadfiles = this.uploadFiles.bind(this);
newFileInput.onchange = uploadfiles;
oldFileInput.parentNode.replaceChild(newFileInput, oldFileInput);
}
private uploadFiles() {
this.onUploadStarted.emit();
const fileInputParentNative = this.fileInputParent.nativeElement;
const fileInput = fileInputParentNative.querySelector('input');
if (fileInput.files && fileInput.files.length > 0) {
const formData = new FormData();
for (let i = 0; i < fileInput.files.length; i++) {
formData.append('files', fileInput.files[i]);
}
const onUploaded = this.onUploaded;
const onError = this.onError;
const addFileInput = this.addFileInput.bind(this);
fetch('/api/Data/UploadFiles', {
credentials: 'include',
method: 'POST',
body: formData,
}).then((response: any) => {
if (response.status !== 200) {
const error = `An error occured. Status: ${response.status}`;
throw new Error(error);
}
return response.json();
}).then(files => {
onUploaded.emit(files);
addFileInput();
}).catch((error) => {
onError.emit(error);
});
}
This is useful tutorial,如何使用NG2文件上传和无NG2文件上传上传文件。
对我来说有很大帮助。
目前,教程包含了两个错误:
1,客户应具有相同的上传网址作为服务器,因此在app.component.ts
变线
const URL = 'http://localhost:8000/api/upload';
至
const URL = 'http://localhost:3000';
2-服务器发送响应为“text / html的”,所以在app.component.ts
变化
.post(URL, formData).map((res:Response) => res.json()).subscribe(
//map the success function and alert the response
(success) => {
alert(success._body);
},
(error) => alert(error))
至
.post(URL, formData)
.subscribe((success) => alert('success'), (error) => alert(error));
要上传与表单域图像
SaveFileWithData(article: ArticleModel,picture:File): Observable<ArticleModel>
{
let headers = new Headers();
// headers.append('Content-Type', 'multipart/form-data');
// headers.append('Accept', 'application/json');
let requestoptions = new RequestOptions({
method: RequestMethod.Post,
headers:headers
});
let formData: FormData = new FormData();
if (picture != null || picture != undefined) {
formData.append('files', picture, picture.name);
}
formData.append("article",JSON.stringify(article));
return this.http.post("url",formData,requestoptions)
.map((response: Response) => response.json() as ArticleModel);
}
在我来说,我需要的.NET Web API中的C#
// POST: api/Articles
[ResponseType(typeof(Article))]
public async Task<IHttpActionResult> PostArticle()
{
Article article = null;
try
{
HttpPostedFile postedFile = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count == 1)
{
postedFile = httpRequest.Files[0];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
var json = httpRequest.Form["article"];
article = JsonConvert.DeserializeObject <Article>(json);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
article.CreatedDate = DateTime.Now;
article.CreatedBy = "Abbas";
db.articles.Add(article);
await db.SaveChangesAsync();
}
catch (Exception ex)
{
int a = 0;
}
return CreatedAtRoute("DefaultApi", new { id = article.Id }, article);
}