Pdf 可以被视为一个文件。您可以使用 byte[] 来传输文件。下面是我的简单示例。
我的合同。
[ServiceContract()]
public interface IFileUpload
{
[OperationContract]
void Upload(byte[] bys);
}
我的服务。AspNetCompatibilityRequirementsMode.Allowed 用于启用 HttpContext,否则将为空。这里我直接将文件保存在服务器中,如果要保存在 sqlserver 中,只需使用 varbinary 字段保存 pdf 文件的 byte[] 即可。
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class FileUploadService : IFileUpload
{
public void Upload(byte[] bys)
{
string filename = Guid.NewGuid().ToString()+".pdf";
File.WriteAllBytes(HttpContext.Current.Request.MapPath("/upload/") + filename, bys);
}
}
我的 wcf 服务的 web.config。bindingconfiguration ECMSBindingConfig 用于启用上传大数据或服务不允许太大数据。serviceHostingEnvironment 的 aspNetCompatibilityEnabled 也应设置为 true,否则 HttpContext 将为空。
<service name="Service.CalculatorService" >
<endpoint binding="basicHttpBinding" bindingConfiguration="ECMSBindingConfig" contract="ServiceInterface.ICalculatorService"></endpoint>
</service>
<bindings>
<basicHttpBinding>
<binding name="ECMSBindingConfig" allowCookies="false" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647" bypassProxyOnLocal="true" >
<readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" maxDepth="2147483647"
maxBytesPerRead="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
/>
我的客户。用户网络表单作为示例。
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="upload" OnClick="Button1_Click" />
</form>
后面的代码。这里我使用的是 channelFacotory ,它类似于 Visual Studio 生成的客户端
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile file = FileUpload1.PostedFile;
using (ChannelFactory<IFileUpload> uploadPdf = new ChannelFactory<IFileUpload>("upload"))
{
IFileUpload fileUpload = uploadPdf.CreateChannel();
byte[] bys = new byte[file.InputStream.Length];
file.InputStream.Read(bys, 0, bys.Length);
fileUpload.Upload(bys);
}
}
客户端的 Web.config。
<client>
<endpoint name ="upload" address="http://localhost:62193/uploadPdf.svc" binding="basicHttpBinding" contract="ServiceInterface.LargeData.IFileUpload" />
</client>
我假设用户上传 pdf,如果你想上传其他文件,你可以添加文件扩展名作为服务的参数。其他操作应该类似。