angular 2 表单数据为空
angular 2 formdata empty
我无法将数据传递给 FormData。我搜索过。但我无法理解。请你帮助我好吗。
我的目标; image file save using web API 2.我没有写更多的wep api 2.
我找不到解决办法。还有其他使用方法吗?
我的组件
let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file;
if ($('#fileinput')[0] != undefined) {
if ($('#fileinput')[0].files.length > 0) {
file = $('#fileinput')[0].files[0];
formData.append('uploadingFile', file);
//fp.fileName = file.name;
console.log(formData);
}
formData.append('siparisid', this.siparis.siparisid);
formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
formData.append('aciklama',this.form.controls.aciklamaFormController.value);
this.fileUploadService.kaydet(
formData
)
.subscribe(result => {
console.log(result);
if (result === true) {
this.errorMessages = [];
this.dialogRef.close(true)
}
else
this.errorMessages = ['Kayıt Yapılamadı'];
},
err => {
if (err.status == 0) {
this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
}
else if (err.status == 404) {
this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
}
else if (err.status == 401) {
this.errorMessages = ['Yetki Hatası.'];
}
else if (err.status == 400) {
let errBody = JSON.parse(err._body);
if (errBody
&& errBody['error'] == 'invalid_grant')
this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
else
this.errorMessages = [errBody.message];
}
else
this.errorMessages = [err.statusTest]
}
);
}
**my Service**
public kaydet(
formData: FormData
): Observable<any> {
let postFiles = {
formData: formData
};
return this.http.post(
this.apiUrl + '/dokumanlar/ResimKaydet',
JSON.stringify(postFiles)
)
.map(res => res.json());
}
formData=formData {} >> 这样是空的
要将 image(avatar)
发送到服务器或网络 api,您可以使用 FormData
,如果您想达到此目的,请逐步完成这些工作:
在 html 文件中使用 #avatar
访问组件中的 ElementRef
:
<form (ngSubmit)="onSubmit()">
<input type="file" accept=".png, .jpg, .jpeg" #avatar>
</form>
创建 component
并用于 sending image
服务器;
import {Component} from '@angular/core';
import {ElementRef} from '@angular/core';
import {ViewChild} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {HttpParams} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';
@Component({
selector: 'app-avatar',
templateUrl: './avatar.component.html',
styleUrls: ['./avatar.component.css']
})
export class AvatarComponent {
@ViewChild('avatar') avatar: ElementRef;
constructor(private http: HttpClient) { }
onSubmit() {
const formData = new FormData();
formData.append('avatar',
this.avatar.nativeElement.files[0],
this.avatar.nativeElement.files[0].name);
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
this.http.post('api/upload', formData, {headers: headers})
.subscribe(
(response) => {
},
(error) => {
}
);
}
}
Notice to adding file to FormData
like below method with parameters
formData.append(name, fileValue, fileName)
我通过FormData传递数据
在我的例子中,我使用了 formData.set(name, fileValue, fileName)
而不是 formData.append
(name, fileValue, fileName)
请参阅 LINK
HTML
<input type="file"
name="fileItem"
id="fileItem"
(change)="handleFileInput($event.target.files)"/>
2.组件
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
this.uploadFileToServer();
}
uploadFileToServer() {
this.fileUploadService.UploadFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});}
3.服务
UploadFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'api/image/upload';
var formData = new FormData();
formData.set('file', fileToUpload);
return this._http
.post(endpoint, formData)
.map(() => { return true; })
.catch((e) => this.handleError(e));}
4。 服务器
[Route("upload")]
public IHttpActionResult UploadImage()
{
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Ok();
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Ok();
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Ok();
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Ok();
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Ok();
}}
我无法将数据传递给 FormData。我搜索过。但我无法理解。请你帮助我好吗。 我的目标; image file save using web API 2.我没有写更多的wep api 2.
我找不到解决办法。还有其他使用方法吗?
我的组件
let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file;
if ($('#fileinput')[0] != undefined) {
if ($('#fileinput')[0].files.length > 0) {
file = $('#fileinput')[0].files[0];
formData.append('uploadingFile', file);
//fp.fileName = file.name;
console.log(formData);
}
formData.append('siparisid', this.siparis.siparisid);
formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
formData.append('aciklama',this.form.controls.aciklamaFormController.value);
this.fileUploadService.kaydet(
formData
)
.subscribe(result => {
console.log(result);
if (result === true) {
this.errorMessages = [];
this.dialogRef.close(true)
}
else
this.errorMessages = ['Kayıt Yapılamadı'];
},
err => {
if (err.status == 0) {
this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
}
else if (err.status == 404) {
this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
}
else if (err.status == 401) {
this.errorMessages = ['Yetki Hatası.'];
}
else if (err.status == 400) {
let errBody = JSON.parse(err._body);
if (errBody
&& errBody['error'] == 'invalid_grant')
this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
else
this.errorMessages = [errBody.message];
}
else
this.errorMessages = [err.statusTest]
}
);
}
**my Service**
public kaydet(
formData: FormData
): Observable<any> {
let postFiles = {
formData: formData
};
return this.http.post(
this.apiUrl + '/dokumanlar/ResimKaydet',
JSON.stringify(postFiles)
)
.map(res => res.json());
}
formData=formData {} >> 这样是空的
要将 image(avatar)
发送到服务器或网络 api,您可以使用 FormData
,如果您想达到此目的,请逐步完成这些工作:
在 html 文件中使用
#avatar
访问组件中的ElementRef
:<form (ngSubmit)="onSubmit()"> <input type="file" accept=".png, .jpg, .jpeg" #avatar> </form>
创建
component
并用于sending image
服务器;import {Component} from '@angular/core'; import {ElementRef} from '@angular/core'; import {ViewChild} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {HttpParams} from '@angular/common/http'; import {HttpHeaders} from '@angular/common/http'; @Component({ selector: 'app-avatar', templateUrl: './avatar.component.html', styleUrls: ['./avatar.component.css'] }) export class AvatarComponent { @ViewChild('avatar') avatar: ElementRef; constructor(private http: HttpClient) { } onSubmit() { const formData = new FormData(); formData.append('avatar', this.avatar.nativeElement.files[0], this.avatar.nativeElement.files[0].name); const headers = new HttpHeaders(); headers.append('Content-Type', 'multipart/form-data'); headers.append('Accept', 'application/json'); this.http.post('api/upload', formData, {headers: headers}) .subscribe( (response) => { }, (error) => { } ); } }
Notice to adding file to
FormData
like below method with parameters
formData.append(name, fileValue, fileName)
我通过FormData传递数据
在我的例子中,我使用了 formData.set(name, fileValue, fileName)
而不是 formData.append
(name, fileValue, fileName)
请参阅 LINK
HTML
<input type="file" name="fileItem" id="fileItem" (change)="handleFileInput($event.target.files)"/>
2.组件
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
this.uploadFileToServer();
}
uploadFileToServer() {
this.fileUploadService.UploadFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});}
3.服务
UploadFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'api/image/upload';
var formData = new FormData();
formData.set('file', fileToUpload);
return this._http
.post(endpoint, formData)
.map(() => { return true; })
.catch((e) => this.handleError(e));}
4。 服务器
[Route("upload")]
public IHttpActionResult UploadImage()
{
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Ok();
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Ok();
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Ok();
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Ok();
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Ok();
}}