将图像上传到WCF服务会降低图像大小并且图像无法打开

时间:2016-04-06 08:21:45

标签: c# asp.net image wcf file-upload

我正在尝试使用WCF服务上传图像和其他文件,图像和其他类型的文件正在上传成功。但我面临的问题是,当我上传几KB的图片时,它会上传,我可以很好地打开它。但是当图像大小很大时,我试图上传800 KB的图像,只有10KB上传,而且它没有打开或者它已经损坏。

我的web.config是这样的:

<?xml version="1.0"?>
<configuration>

  <appSettings>

  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2097151" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"    />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service
          name="ImageUploadingService.Service1"
          behaviorConfiguration="MyServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="webHttpBinding" contract="ImageUploadingService.IService1" behaviorConfiguration="web" />

      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding
          maxBufferPoolSize="2147483647000000"
          maxReceivedMessageSize="2147483647000000"
          maxBufferSize="2147483647" transferMode="StreamedRequest">
        </binding>
      </webHttpBinding>
    </bindings>

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

我的服务合同是这样的:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "PostImage?fileName={fileName}&Ext={Ext}&Path={Path}", Method = "POST")]
    string PostImage(Stream sm,string fileName,string Ext,string Path);
}

我的服务类是这样的:

public class Service1 : IService1
{
    public string PostImage(Stream stream, string fileName, string Ext, string Path)
    {
        byte[] buffer = new byte[10000];
        stream.Read(buffer, 0, 10000);
        FileStream f = new FileStream(Path+fileName   , FileMode.OpenOrCreate);
        f.Write(buffer, 0, buffer.Length);
        f.Close();
        stream.Close();
        return "Recieved the image on server";
    }
}

我上传的代码是这样的:

protected void btnUploadImage_Click(object sender, EventArgs e)
{
    PostData();
}
public void PostData()
{   
    string FileName="";
    string ext="";
    try
    {
        byte[] fileToSend = null; 

        if (FileUpload1.HasFile)
        {
            ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
            FileName = FileUpload1.FileName;
            Stream stream = FileUpload1.FileContent;
            stream.Seek(0, SeekOrigin.Begin);
            fileToSend = new byte[stream.Length];
            int count = 0;
            while (count < stream.Length)
            {
                fileToSend[count++] = Convert.ToByte(stream.ReadByte());
            }
        }

        //Here provide your service location url in below line. You need to host your service on server(IIS or which one you prefer)
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:49287/Service1.svc/PostImage?fileName="+FileName+"&Ext="+ ext +"&Path=C:\\Users\\mubashir.gul\\Documents\\mydocs\\");//PostImage?fileName={fileName}&Ext={Ext}&Path={Path}

        req.Method = "POST";
        req.ContentType = "application/octet-stream"; 
        req.ContentLength = fileToSend.Length;
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(fileToSend, 0, fileToSend.Length);
        reqStream.Close();

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        StreamReader reader = new StreamReader(resp.GetResponseStream());
        string result = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

任何类型的建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

您的服务代码包含以下行:

    byte[] buffer = new byte[10000];
    stream.Read(buffer, 0, 10000);

你说的约10 Kb。

尝试将服务方法更改为以下内容:

    FileStream f = new FileStream(Path+fileName   , FileMode.OpenOrCreate);
    stream.CopyTo(f);
    f.Close();
    stream.Close();