我看了几个问题和答案,但无法解决我的问题。我的代码如下:
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接受了答案的代码。有人能帮我弄清楚可能出了什么问题吗?
FileUpload非常容易使用angular。你可以使用这个描述here或按照我的步骤。
在组件模板中,只需将更改事件附加到输入,然后让它调用处理要上载的文件的函数。 $ event.target.files包含您的文件。
<input type="file" (change)="upload($event.target.files)">
在组件类中,您需要导入files.service.ts(或者您曾经称之为的文件)并在您的关注模块或组件本身中提供它,如果您不想重复使用它。
import { FilesService } from 'PATHTO/files.service';
[...]
contructor(private filesService: FilesService) { }
然后,您可以在组件类中实现以下函数以进行单个文件上载,否则循环遍历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替换为静态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,但我认为必须有一个等价的。
希望这有帮助,祝你有愉快的一天!干杯。
这样我就可以在项目中将上传图像实现到web 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";
}
);
}
服务TS
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);
}