【问题标题】:WCF/C# upload a fileWCF/C# 上传文件
【发布时间】:2015-12-10 04:00:49
【问题描述】:

我目前正在使用 C# 和 WCF 开发 Web 服务。我需要制作一个上传方法,所以我关注this tutorial。现在我可以通过表单上传文件,文件上传到文件夹中,但在浏览器中总是返回错误(如在 ajax 中指定)这里所有代码:

IWebService.cs

[ServiceContract]
public interface IWebService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
    void UploadFile(string fileName, Stream stream);
}

WebService.svc

public void UploadFile(string fileName, Stream stream)
{
    string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);

    int length = 0;
    using (FileStream writer = new FileStream(FilePath, FileMode.Create))
    {
        int readCount;
        var buffer = new byte[8192];
        while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            writer.Write(buffer, 0, readCount);
            length += readCount;
        }
    }
}

TestClient.html

<head>
<script type="text/javascript">
    function UploadFile() {
        fileData = document.getElementById("fileUpload").files[0];
        var data = new FormData();

        $.ajax({
            url: 'http://localhost:1945/Service1.svc/UploadFile?fileName=' + fileData.name,
            type: 'POST',
            data: fileData,
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: "application/octet-stream", // Set content type to false as jQuery will tell the server its a query string request
            success: function (data) {
                alert('successful..');
            },
            error: function (data) {
                alert('Some error Occurred!');
            }
        });
    }

</script>
<title></title>
</head>
<body>
<div>
    <div>
        <input type="file" id="fileUpload" value="" />
        <br />
        <br />
        <button id="btnUpload" onclick="UploadFile()">
            Upload
        </button>
    </div>
</div>
</body>

【问题讨论】:

    标签: c# wcf


    【解决方案1】:

    我试图以我的方式解决你的问题

    1. 将 UploadCustomFile 方法的 retun 类型更改为 String 并返回一个虚拟消息

      public String UploadCustomFile(string fileName, System.IO.Stream stream) { string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);

      int length = 0;
      using (FileStream writer = new FileStream(FilePath, FileMode.Create))
      {
          int readCount;
          var buffer = new byte[8192];
          while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
          {
              writer.Write(buffer, 0, readCount);
              length += readCount;
          }
      }
      
          try
          {
              //do something else
          }
          catch
          {      
                  //to return custom error message - ajax will catch this as a error
                  HttpContext.Current.Response.Write("");
                  return "not okey";
          }
      
      return "okey";
      }
      
    2. 添加ResponseFormat = WebMessageFormat.Json和String返回类型改变接口方法

      [OperationContract]
      [WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
      String UploadCustomFile(string fileName, Stream stream);
      

    当我尝试这种方式时,我收到了成功警报消息

    从服务器端发送自定义异常

    【讨论】:

    • 感谢您的评论对我有很大帮助。你知道我需要为错误添加的回报吗?
    猜你喜欢
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多