尝试将文件从javascript上传到WCF Web服务

时间:2019-01-22 12:24:00

标签: wcf httpresponse file-transfer httpcontext ionic4

我正在尝试将文件从ionic上载到外部服务上的WCF Web服务。

我想我非常了解TypeScript,但是我是ASP.NET中文件传输的新手。我尝试了许多解决方案,但都无济于事。我不确定要使用哪种解决方案,所以我想在这里问。

到目前为止,这是我的离子代码。

doImageUpload() {
  let loader = this.loadingCtrl.create({
    content: "Uploading..."
  });
  loader.present();

  let filename = this.imageURI.replace(/^file:\/\//, '');

  //let filename = this.imageURI.split('/').pop();

  //filename = filename.replace(/^file:\/\//, '');

   console.log('imageURI', filename);
  console.log('imageURIoriginal', this.imageURI);
  const fileTransfer: FileTransferObject = this.transfer.create();

  let options: FileUploadOptions = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,
    mimeType: "image/jpg",
    params: { 'title': this.imageTitle }
  };
fileTransfer.upload(filename,"http://172.16.8.110:58482/TweetService.svc/uploadImage",options).then((res)=>{
    console.log('success', res);

  },(err)=>{
    console.log('fail', err);
  });

}

我从网络上提取的网络服务如下。

    [OperationContract]
    [HttpPost]
    [Route("upload")]
    public HttpResponseMessage uploadImage()
    {
        var request = HttpContext.Current.Request;

        if (Request.Content.IsMimeMultipartContent())
        {
            if (request.Files.Count > 0)
            {
                var postedFile = request.Files.Get("file");
                var title = request.Params["title"];
                string root = HttpContext.Current.Server.MapPath("~/Files");
                root = root + "/" + postedFile.FileName;
                postedFile.SaveAs(root);
            //Save post to DB
            return Request.CreateResponse(System.Net.HttpStatusCode.Found, new
            {
                error = false,
                status = "created",
                path = root
            });
            return null;

            }
        }

        return null;
    }

立即引发的错误是“找不到请求”。我不知道这是否应该是“请求”,但是无论哪种方式,由于“内容”都不是HTTPContext的成员,因此仍然无法使用。

有人知道最好的方法吗?

编辑:

显然,在WCF 4.5中,它会在触发任何方法之前运行“缓冲流”,因此不会在“经典”模式下运行。我添加了一些代码来解决这个问题。

我精简了代码,现在该方法不再接收并出现错误,但是我现在收到500错误,表明参数或其传递方式有问题。这是我收到的错误

Error Message

这是更新的C#方法。

[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = 
"POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = 
WebMessageFormat.Json)]
public string SaveImage()
{
    HttpPostedFile file = HttpContext.Current.Request.Files["recFile"];
    return "somestring";
}

这是离子代码。

const fileTransfer: FileTransferObject = this.transfer.create();

let options: FileUploadOptions = {
    fileKey: "recFile",
    fileName: this.imageURI,
    chunkedMode: false,
    mimeType: "image/jpg",
    params: { 'title': this.imageTitle }
};

fileTransfer.upload(this.imageURI, "http://172.16.8.110:58482/TweetService.svc/uploadImage",options).then((res)=> 
 {
  console.log('success', res);

},(err)=>{
  console.log('fail', err);
});

0 个答案:

没有答案