Angular 文件上传的角度?

Angular 文件上传的角度?,angular,file-upload,angular2-http,Angular,File Upload,Angular2 Http,我知道这是一个非常普遍的问题,但我无法在Angular 2中上传文件。 我试过了 1) 及 (二) ……但失败了。有人上传过文件吗?你用了什么方法?如何做到这一点?如果提供了任何示例代码或演示链接,我们将不胜感激。我成功地使用了以下启动工具。我在与Priming的比赛中没有任何利害关系,只是把我的建议传给别人 Angular 2为上传文件提供了良好的支持。不需要第三方库 fileChange(事件){ let fileList:fileList=event.target.files; 如果(

我知道这是一个非常普遍的问题,但我无法在Angular 2中上传文件。 我试过了

1) 及

(二)


……但失败了。有人上传过文件吗?你用了什么方法?如何做到这一点?如果提供了任何示例代码或演示链接,我们将不胜感激。

我成功地使用了以下启动工具。我在与Priming的比赛中没有任何利害关系,只是把我的建议传给别人


Angular 2为上传文件提供了良好的支持。不需要第三方库


fileChange(事件){
let fileList:fileList=event.target.files;
如果(fileList.length>0){
let file:file=fileList[0];
让formData:formData=newformdata();
append('uploadFile',file,file.name);
let headers=新的headers();
/**在Angular 5中,包含标题内容类型可能会使您的请求无效*/
headers.append('Content-Type','multipart/formdata');
headers.append('Accept','application/json');
let options=newrequestoptions({headers:headers});
this.http.post(`this.apidendpoint}`,formData,options)
.map(res=>res.json())
.catch(错误=>Observable.throw(错误))
.订阅(
data=>console.log('success'),
error=>console.log(错误)
)
}
}

使用@angular/core:“~2.0.0”和@angular/http:“~2.0.0”

多亏了@Eswar。这段代码对我来说非常有效。我想在解决方案中添加一些东西:

我收到错误:
java.io.IOException:RESTEASY007550:无法获取多部分的边界

为了解决此错误,您应该删除“内容类型”“多部分/表单数据”。它解决了我的问题。

,如何使用ng2文件上载和不使用ng2文件上载上载上载文件

对我来说,这很有帮助

目前,本教程包含几个错误:

1-客户端应具有与服务器相同的上载url, 所以在
app.component.ts
中更改行

consturl='1〕http://localhost:8000/api/upload“;

consturl='1〕http://localhost:3000“;

2-服务器将响应发送为“text/html”,因此在
app.component.ts
change中

.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));

这个简单的解决方案适合我:file-upload.component.html

如果使用的是dotnet core,则参数名必须与“发件人”字段名相匹配。在这种情况下,文件名为:

[HttpPost("[action]")]
public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files)
{
  return await _binaryService.UploadFilesAsync(files);
}
[HttpPost(“[action]”)
公共异步任务上载文件(列表文件)
{
返回wait\u binaryService.uploadFileAsync(文件);
}
这个答案是剽窃的

编辑: 上载后,您必须清除文件上载,以便用户可以选择一个新文件。并且,与其使用XMLHttpRequest,不如使用fetch:

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);
      });
    }
private addFileInput(){
const fileInputParentNative=this.fileInputParent.nativeElement;
const oldFileInput=fileinputpparentnative.querySelector('input');
const newFileInput=document.createElement('input');
newFileInput.type='file';
newFileInput.multiple=true;
newFileInput.name='fileInput';
const uploadfiles=this.uploadfiles.bind(this);
newFileInput.onchange=上传文件;
oldFileInput.parentNode.replaceChild(newFileInput,oldFileInput);
}
私有上传文件(){
this.onUploadStarted.emit();
const fileInputParentNative=this.fileInputParent.nativeElement;
const fileInput=fileInputParentNative.querySelector('input');
如果(fileInput.files&&fileInput.files.length>0){
const formData=new formData();
for(设i=0;i{
如果(response.status!==200){
const error=`发生错误。状态:${response.Status}`;
抛出新错误(Error);
}
返回response.json();
})。然后(文件=>{
onUploaded.emit(文件);
addFileInput();
}).catch((错误)=>{
onError.emit(错误);
});
}

由于代码示例有点过时,我想我应该分享一种更新的方法,使用Angular 4.3和新的(er)HttpClient API@Angular/common/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
}

在Angular 2+中,将内容类型保留为空是非常重要的。如果将“内容类型”设置为“多部分/表单数据”,则上载将不起作用

upload.component.html

<input type="file" (change)="fileChange($event)" name="file" />

我已经使用引用上传了文件。这样上传文件不需要包

//要写入.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>

根据上面的答案,我用Angular 5.x构建了这个

只需调用
uploadFile(url,file).subscribe()
即可触发上载

从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient,HttpParams,HttpRequest,HttpEvent};
从“rxjs”导入{observeable};
@可注射()
导出类上载服务{
构造函数(私有http:HttpClient){}
//来自event.target.files[0]的文件
上传文件(url:string,file:file):可观察{
设formData=new formData();
formData.append('upload',file);
设params=newhttpparams();
常量选项={
params:params,
报告进展:是的,
};
const req=new HttpRequest('POST',url,formData,options);
返回这个.http.request(req);
}
}
在组件中这样使用它

//在拖动时
@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,
            });
        });
  }
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);
<input type="file" #fileInput>
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);
} 
// 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);
}
    import { FileUploadModule } from 'ng2-file-upload';

    ------
    ------
    imports:      [ FileUploadModule ],
    ------
    ------
    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);

      }
    ------
    ------
 <input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
this.http.post("http://destinationurl.com/endpoint", fileFormData)
  .subscribe(response => {
    //handle response
  }, err => {
    //handle error
  });
import * as jsPDF from 'jspdf';
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient)

upload() {
    const pdf = new jsPDF()
    const blob = pdf.output('blob')
    const formData = new FormData()
    formData.append('file', blob)
    this.http.post('http://your-hostname/api/upload', formData).subscribe()
}