使用ionic框架和web API上传文件到服务器

oxalkeyp  于 2023-03-16  发布在  Ionic
关注(0)|答案(1)|浏览(186)

我尝试上传视频文件到远程服务器使用离子框架电容器和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,
        });
 
}
368yc8dk

368yc8dk1#

最后我找到了解决办法,
以下代码适用于android和iOS:
upload.html:

<ion-button color="dark" (click)="selectVideo()"></ion-button>

upload.ts:

const options: CameraOptions = {
        sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, 
        mediaType: this.camera.MediaType.VIDEO      
      }
        this.camera.getPicture(options).then(async (videoUrl) => {
          debugger;
          this.selectvideopath=videoUrl;
          const fileTransfer: FileTransferObject = this.transfer.create();
          const options: FileUploadOptions = {
            fileKey: 'file',
            fileName: "<yourfilename>.mp4",
            headers: {},
            params: {}
          };
          const apiUrl = 'http://example.com/api/Upload';
          try {
              const response = await fileTransfer.upload(this.selectvideopath, apiUrl, options);
              console.log('Upload success: ' + response.responseCode);
            } catch (error) {
              console.error('Error uploading file: ' + JSON.stringify(error));
            }
          console.log(this.selectvideopath);
         }, (err) => {
          // Handle error
         });

相关问题