Ami*_*mir 7 form-data asp.net-web-api2 angular
我看了几个问题和答案,但无法解决我的问题.我的代码如下:
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>
Run Code Online (Sandbox Code Playgroud)
零件
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this._dishAddService.postFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)
服务
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);
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
当请求命中API时,文件计数为0.我花了整整两天的时间来弄清楚出了什么问题,但也找不到错误.我不认为代码有问题,因为对于其他一些代码它是有效的.我从不同的SO接受了答案的代码.有人能帮我弄清楚可能出了什么问题吗?
使用 Angular 进行文件上传非常简单。您可以在此处使用此说明 或按照我的步骤操作。
在您的组件模板中,只需将更改事件附加到您的输入,并让它调用处理要上传的文件的函数。$event.target.files包含您的文件。
<input type="file" (change)="upload($event.target.files)">
Run Code Online (Sandbox Code Playgroud)
在您的组件类中,您需要导入files.service.ts(或您所称的任何名称),并在您的相关模块或组件本身中提供它(如果您不想重用它)。
<input type="file" (change)="upload($event.target.files)">
Run Code Online (Sandbox Code Playgroud)
然后,您可以在组件类中实现以下函数以进行单个文件上传,否则循环遍历 files.item 并将其附加到 formData
import { FilesService } from 'PATHTO/files.service';
[...]
contructor(private filesService: FilesService) { }
Run Code Online (Sandbox Code Playgroud)
确保您已在您的环境中定义了 url 属性,或将帖子 url 替换为静态 url。例如,files.service.ts可以如下所示
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 */
);
}
Run Code Online (Sandbox Code Playgroud)
例如,在 php 服务器端,您可以使用$_FILES变量捕获这些文件。对 Asp.net 不太了解,但我认为必须有一个等价物。
希望这有帮助,祝你有美好的一天!干杯。
| 归档时间: |
|
| 查看次数: |
5741 次 |
| 最近记录: |