我尝试上传视频文件到远程服务器使用离子框架电容器和webApi。但当运行代码时,它显示错误,如Invalid 'HttpContent' instance provided.它没有以'multipart/'开头的内容类型头。参数名:含有离子。
我的代码:MyController.cs(网页应用程序):
[Route("api/Upload")]
public async Task<string> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
await content.ReadAsMultipartAsync(provider);
string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));
if (File.Exists(originalFileName))
{
File.Delete(originalFileName);
}
File.Move(uploadingFileName, originalFileName);
return "success";
}
catch (Exception ex)
{
return ex.Message;
}
}
webconfig.cs:
<add key="FileUploadLocation" value="D:\Asp.Net\Fileupload" />
upload.html:
<input #fileInput type="file" [multiple]="true" (change)="uploadFiles( fileInput.files ); fileInput.value = null;"/>
upload.ts:
public async uploadFiles( files: File[] ) : Promise<void>
{
Array.from(files).forEach(async(file1:any)=>
{
try
{
this.uploads.push(await this.Service.uploadFile(file1));
}
catch ( error )
{
console.warn( "File upload failed." );
console.error( error );
}
});
}
service.ts:
public async uploadFile( file: File ) : Promise<UploadResult>
{
var result = await this.httpClient.post<ApiUploadResult>("http://12.99.45.21:8021/Mobile/api/Upload",file, // Send the File Blob as the POST body.
{
headers: {
"Content-Type": file.type
},
params: {
clientFilename: file.name,
mimeType: file.type
}
}
)
.toPromise();
return({
name: file.name,
type: file.type,
size: file.size,
url: result.url,
});
}
1条答案
按热度按时间368yc8dk1#
最后我找到了解决办法,
以下代码适用于android和iOS:
upload.html:
upload.ts: