파일 업로드 각도?
이것이 매우 일반적인 질문이라는 것을 알지만 Angular 2에 파일을 업로드하는 데 실패하고 있습니다.난 시도했다.
http://valor-software.com/ng2-file-upload/ 및
2) http://ng2-uploader.com/home
...하지만 실패했습니다.Angular에 파일을 업로드한 사람이 있습니까?어떤 방법을 사용하셨나요?어떻게 하는 거지?샘플 코드나 데모 링크가 제공되면 정말 감사하겠습니다.
Angular 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 < 1) {
return;
}
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)
);
}
@px/core" 사용: "~2.0.0" 및 @px/core: "~2.0.0"
위의 답변에서 Angular 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");
}
)
}
@에스와르 덕분입니다.이 코드는 저에게 완벽하게 작동했습니다.솔루션에 다음과 같은 몇 가지 사항을 추가하고자 합니다.
오류가 발생했습니다.java.io.IOException: RESTEASY007550: Unable to get boundary for multipart
이 오류를 해결하려면 "Content-Type" "multipart/form-data"를 제거해야 합니다.그것이 제 문제를 해결했습니다.
코드 샘플이 약간 구식이기 때문에 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+에서는 내용 유형을 비워 두는 것이 매우 중요합니다.'Content-Type'을 'multipart/form-data'로 설정하면 업로드가 작동하지 않습니다!
upload.component.vmdk
<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와의 게임에서 제 제안을 전달하는 것에 관심이 없습니다.
http://www.primefaces.org/primeng/ #/파일 업로드
file-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);
}
}
}
닷넷 코어를 사용하는 경우 매개 변수 이름이 원본 필드 이름과 일치해야 합니다.이 경우 파일:
[HttpPost("[action]")]
public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files)
{
return await _binaryService.UploadFilesAsync(files);
}
이 답변은 http://blog.teamtreehouse.com/uploading-files-ajax 의 사본입니다.
편집: 업로드 후 파일 업로드를 지워야 사용자가 새 파일을 선택할 수 있습니다.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);
});
}
이 튜토리얼은 ng2-file-upload 및 ng2-file-upload를 사용하여 파일을 업로드하는 방법에 유용합니다.
저에게는 많은 도움이 됩니다.
현재 튜토리얼에는 다음과 같은 몇 가지 오류가 포함되어 있습니다.
하므로 1 - 클언트을서동일 URL합에 있습니다.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);
}
저의 경우 C#에 .NET Web API가 필요했습니다.
// 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);
}
오늘 나는 ng2-file-upload 패키지를 나의 angular 6 애플리케이션에 통합했다, 그것은 꽤 간단했다, 아래의 높은 수준의 코드를 찾아주세요.
ng2-file-vlan 모듈 가져오기
app.s.ts.
import { FileUploadModule } from 'ng2-file-upload';
------
------
imports: [ FileUploadModule ],
------
------
구성 요소 ts 파일 가져오기 파일 업로더
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.vmdk
<input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
작업 중인 온라인 스택블리츠 링크: https://ng2-file-upload-example.stackblitz.io
스택블리츠 코드 예: https://stackblitz.com/edit/ng2-file-upload-example
공식 문서 링크 https://valor-software.com/ng2-file-upload/
하지 마세요.options
this.http.post(${this.apiEndPoint}, formData)
하세요.globalHeaders
당신의 Http 공장에서.
jspdf 및 Angular 8
pdf를 생성하고 POST 요청과 함께 pdf를 업로드하려고 합니다. 이렇게 합니다(명확하게 하기 위해 일부 코드 및 서비스 계층을 삭제합니다).
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()
}
참고 자료를 이용하여 파일을 업로드했습니다.이 방법으로 파일을 업로드하는 데 패키지가 필요하지 않습니다.
.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 6/7에서 작동합니다.
this.http.post("http://destinationurl.com/endpoint", fileFormData)
.subscribe(response => {
//handle response
}, err => {
//handle error
});
완전한 구현은 다음과 같습니다.
언급URL : https://stackoverflow.com/questions/40214772/file-upload-in-angular
'programing' 카테고리의 다른 글
서브스크립션 배열 대신 SubSink를 사용하는 이유 (0) | 2023.06.28 |
---|---|
Oracle 및 SQL Server 성능 테스트를 게시하는 것은 라이센스 위반입니까? (0) | 2023.06.28 |
스프링 부트 앱에서 META-INF/MANIFEST.MF 파일을 읽는 방법은 무엇입니까? (0) | 2023.06.28 |
Git 저장소에서 삭제된 여러 파일을 제거하는 방법 (0) | 2023.06.28 |
기본 및 하위 클래스를 사용한 Python 장치 테스트 (0) | 2023.06.28 |