【问题标题】:Uploading image to WCF service gets image size reduced and image is not opening将图像上传到 WCF 服务会减小图像大小并且图像无法打开
【发布时间】:2016-07-26 12:24:47
【问题描述】:

我正在尝试使用 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;
    }
}

我们将不胜感激任何类型的建议。

【问题讨论】:

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


    【解决方案1】:

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

        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();
    

    【讨论】:

    • 非常感谢@Igor..工作顺利....但是当我选择超过 20mb 的文件时页面崩溃...请提供任何建议。
    • 我打赌你可能会遇到一些超时。据我了解,您遇到了一些异常(您已经尝试/捕获您的代码)。您能否发布您遇到的异常 - 然后我将能够更好地告诉如何处理它。
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2012-07-15
    • 2018-05-28
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多