WCF / C#上传文件

时间:2015-12-10 04:00:50

标签: c# wcf

我目前正在使用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>

1 个答案:

答案 0 :(得分:2)

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

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

    public String UploadCustomFile(string fileName,System.IO.Stream stream) {     string FilePath = Path.Combine(HostingEnvironment.MapPath(&#34;〜/ FileServer / Uploads&#34;),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);
    
  3. 当我尝试这种方式时,我得到了成功警报信息

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