将图像上传到网络 Api 2 使用 angular 5
Upload image to Web Api 2 Using angular 5
我看了几个 SO 问题和答案,但无法解决我的问题。我的代码如下:
HTML
<input type="file" id="file" accept="image/*" name="File" (change)="handleFileInput($event.target.files)">
<button type="button" mat-raised-button color="primary" (click)="uploadFileToActivity()">Upload</button>
组件
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this._dishAddService.postFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});
}
服务
postFile(fileToUpload: File): Observable<boolean> {
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.httpRequestUrl + 'api/dish/UploadDishImage', formData, options)
.map(
(response => response.json()))
.catch(CommonFunctionService.handleError);
}
API
[HttpPost]
[ActionName("UploadDishImage")]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}
当请求到达 API 时,文件数为 0。我花了整整两天时间弄清楚出了什么问题,但也无法找出错误。我不认为代码有问题,因为对于其他代码来说它是有效的。我从不同的 SO 接受的答案中获取了代码。谁能帮我弄清楚可能出了什么问题?
使用 angular 上传文件非常简单。您可以使用此说明 或按照我的步骤操作。
在您的组件模板中,只需将一个更改事件附加到您的输入并让它调用一个函数来处理要上传的文件。 $event.target.files 包含您的文件。
<input type="file" (change)="upload($event.target.files)">
在你的组件中 class 你需要导入你的 files.service.ts (或者你怎么称呼它)并在你的相关模块中提供它或者如果您不想重用它,请在组件本身中。
import { FilesService } from 'PATHTO/files.service';
[...]
contructor(private filesService: FilesService) { }
然后你可以在你的组件class中实现下面的功能,用于单个文件上传,否则循环files.item并附加到formData
upload(files: FileList) {
const file = files.item(0);
this.filesService.upload(file).subscribe(
res => /* Place your success actions here */,
error => /* Place your error actions here */
);
}
确保您已经在您的环境中定义了一个 url 属性,或者将 post url 替换为静态属性。例如 files.service.ts 可以是这样的
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { environment } from 'PATHTO/environments/environment';
@Injectable()
export class FilesService {
constructor(private http: HttpClient) { }
upload(file: File): Observable<Object> {
const formData: FormData = new FormData();
formData.append('avatar', file, file.name);
return this.http.post(`${environment.url}avatar.php`, formData);
}
}
例如,在 php 服务器端,您可以使用 $_FILES 变量捕获这些文件。不太了解 Asp.net 但我认为必须有一个等价关系。
希望这对您有所帮助,祝您有愉快的一天!干杯。
通过这种方式,我在项目中实现了上传图片到网络API。
我为谁分忧
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
循序渐进
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML形式
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)"/>
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i class="material-icons">save</i></button>
</div>
</form>
要使用的 TS 文件 API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
服务技术支持
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
我看了几个 SO 问题和答案,但无法解决我的问题。我的代码如下:
HTML
<input type="file" id="file" accept="image/*" name="File" (change)="handleFileInput($event.target.files)">
<button type="button" mat-raised-button color="primary" (click)="uploadFileToActivity()">Upload</button>
组件
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this._dishAddService.postFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});
}
服务
postFile(fileToUpload: File): Observable<boolean> {
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.httpRequestUrl + 'api/dish/UploadDishImage', formData, options)
.map(
(response => response.json()))
.catch(CommonFunctionService.handleError);
}
API
[HttpPost]
[ActionName("UploadDishImage")]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}
当请求到达 API 时,文件数为 0。我花了整整两天时间弄清楚出了什么问题,但也无法找出错误。我不认为代码有问题,因为对于其他代码来说它是有效的。我从不同的 SO 接受的答案中获取了代码。谁能帮我弄清楚可能出了什么问题?
使用 angular 上传文件非常简单。您可以使用此说明
在您的组件模板中,只需将一个更改事件附加到您的输入并让它调用一个函数来处理要上传的文件。 $event.target.files 包含您的文件。
<input type="file" (change)="upload($event.target.files)">
在你的组件中 class 你需要导入你的 files.service.ts (或者你怎么称呼它)并在你的相关模块中提供它或者如果您不想重用它,请在组件本身中。
import { FilesService } from 'PATHTO/files.service';
[...]
contructor(private filesService: FilesService) { }
然后你可以在你的组件class中实现下面的功能,用于单个文件上传,否则循环files.item并附加到formData
upload(files: FileList) {
const file = files.item(0);
this.filesService.upload(file).subscribe(
res => /* Place your success actions here */,
error => /* Place your error actions here */
);
}
确保您已经在您的环境中定义了一个 url 属性,或者将 post url 替换为静态属性。例如 files.service.ts 可以是这样的
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { environment } from 'PATHTO/environments/environment';
@Injectable()
export class FilesService {
constructor(private http: HttpClient) { }
upload(file: File): Observable<Object> {
const formData: FormData = new FormData();
formData.append('avatar', file, file.name);
return this.http.post(`${environment.url}avatar.php`, formData);
}
}
例如,在 php 服务器端,您可以使用 $_FILES 变量捕获这些文件。不太了解 Asp.net 但我认为必须有一个等价关系。
希望这对您有所帮助,祝您有愉快的一天!干杯。
通过这种方式,我在项目中实现了上传图片到网络API。
我为谁分忧
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
循序渐进
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML形式
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)"/>
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i class="material-icons">save</i></button>
</div>
</form>
要使用的 TS 文件 API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
服务技术支持
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}