WCF/C#上载文件

本文关键字:文件 上载 WCF | 更新日期: 2023-09-27 18:26:19

我目前正在使用C#和WCF开发web服务。我需要制作一个上传方法,所以我遵循本教程。现在我可以通过表单上传文件,文件被上传到文件夹中,但在浏览器中。它总是告诉我有一个错误(如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>

WCF/C#上载文件

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

  1. 将UploadCustomFile方法的retun类型更改为String,并返回一条伪消息

    public String UploadCustomFile(字符串文件名,System.IO.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);
    

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

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