C# 图片上传到远程服务器

本文介绍了如何在远程服务器上部署接收图片数据的服务,包括使用Web Service和WCF两种方式,并详细展示了客户端代码实现。

远程服务器上需要部署一个接收图片数据的服务

有很多方式,会慢慢补充过来

客户端代码

使用WebService

 private void button1_Click(object sender, EventArgs e)
        {
            WebService1SoapClient ssc = new WebService1SoapClient();
            byte[] content = getbyte();
            if (ssc.webupfile("jpg", "panlitao", content))
            {
                MessageBox.Show("附件上传成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("附件上传失败!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

使用WCF
        private void button2_Click(object sender, EventArgs e)
        {
            wcfsvc.IwcfupfilesClient lpf = new wcfsvc.IwcfupfilesClient();
            byte[] content = getbyte();
            textBox1.Text = lpf.wcfserverwebupfile("jpg", "panlitao", content);
           


        }



//图片图片转换为byte(选择jpg格式的图片,格式没有严格限制)
        private byte[] getbyte()
        {
            OpenFileDialog dlgOpenFile = new OpenFileDialog();
            dlgOpenFile.Title = "选择要上传的附件";
            dlgOpenFile.Filter = "所有文件(*.*)|*.*";


            if (dlgOpenFile.ShowDialog() == DialogResult.Cancel)
            {
                return null;
            }
            //dlgOpenFile.ValidateNames = true;
            string sFileName = dlgOpenFile.FileName;
            System.IO.FileStream objectfile = new System.IO.FileStream(sFileName, System.IO.FileMode.Open);






            if (objectfile.Length > 4096000)
            {
                MessageBox.Show("文件大小超过限制,不能上传,请选择4M以内的附件。", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                objectfile.Close();
                return null;
            }


            byte[] content = new byte[objectfile.Length];
            objectfile.Read(content, 0, (int)objectfile.Length);


            if (content != null)
            {
                sFileName = sFileName.Substring(sFileName.LastIndexOf("\\") + 1);


                WebService1SoapClient wsc = new WebService1SoapClient();


            }
            objectfile.Close();
            return content;
        }

1.在服务器上放置一个webservice

 [WebMethod]
        public bool webupfile(String filetype, String filename, Byte[] coutent)
        {
            MemoryStream ms = new MemoryStream(coutent, 0, coutent.Length);
            File.WriteAllBytes("U:\\ceshiweb\\" + filename + "." + filetype, coutent);
          
            return true;
        }

2.WCF 我是部署在IIS上的,其他的寄宿方式以后加上来

   public String wcfserverwebupfile(String filetype, String filename, Byte[] coutent)
       {
            try
            {
             MemoryStream ms = new MemoryStream(coutent, 0, coutent.Length);
            File.WriteAllBytes("U:\\ceshiweb\\" + filename + "." + filetype, coutent);
                return "1454";
            }
            catch (System.Exception ex)
            {
                return ex.ToString() ;
            }
           
          
       }


WCF 上传文件有大小的配置下边给出在服务器的配置,属性具体意思我就不描述了。服务器默认可能没有bingdings 自己添加上就行了,如果不配置,上传文件文件稍微大点的时候会报异常,测试过程中60kb的默认配置就会出现异常

  <bindings>
      <basicHttpBinding>
        <binding name="LargeDataTransferServicesBinding" sendTimeout="00:10:00"
          maxBufferPoolSize="10485760" maxBufferSize="10485760" maxReceivedMessageSize="2147483647"
          transferMode="Streamed" messageEncoding="Text">
          <readerQuotas maxStringContentLength="10485760" maxArrayLength="10485760"
            maxBytesPerRead="10485760" />
        </binding>
      </basicHttpBinding>
    </bindings>


    <services>
      <service name="WCFdome.wcfupfiles">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="LargeDataTransferServicesBinding"
          contract="WCFdome.Iwcfupfiles" />
        <host>
          <timeouts openTimeout="00:10:00" />
        </host>
      </service>
    </services>

### C# 实现向远程服务器上传图片 为了实现从C#应用程序向远程服务器上传图片的功能,可以采用多种方法。一种常见的方式是利用`HttpClient`类来发送HTTP请求并处理文件传输。 #### 使用 `HttpClient` 类进行文件上传 这种方法适用于现代.NET框架版本,并提供了更简洁的API接口: ```csharp using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public class ImageUploader { public async Task UploadImageAsync(string url, string filePath) { using (var client = new HttpClient()) using (var content = new MultipartFormDataContent()) using (var fileStream = File.OpenRead(filePath)) { var fileContent = new StreamContent(fileStream); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = Path.GetFileName(filePath) }; content.Add(fileContent); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); } } } ``` 这段代码创建了一个名为`ImageUploader`的类,其中包含异步方法`UploadImageAsync`用于执行实际的文件上传操作[^1]。 对于较旧的应用程序或特定场景下,则可能需要用到`WebClient`类来进行简单的文件上传任务: ```csharp using System; using System.Net; public void UploadFileUsingWebClient(string uriString, string fileNamePath) { using (WebClient myWebClient = new WebClient()) { myWebClient.UploadFile(uriString, "PUT", fileNamePath); } } ``` 此函数展示了如何使用`WebClient`对象及其内置方法完成文件上传过程[^2]。 另外还有一种基于文件流的方式来处理大文件或其他特殊需求的情况: ```csharp using System; using System.IO; using System.Net.Sockets; public void UploadLargeFileViaSocket(string serverAddress, int port, string localFilePath) { TcpClient tcpClient = new TcpClient(serverAddress, port); byte[] buffer = new byte[4096]; using (NetworkStream networkStream = tcpClient.GetStream()) using (FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read)) { int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { networkStream.Write(buffer, 0, bytesRead); } // 发送结束标志位给服务端表示数据已全部接收完毕 networkStream.WriteByte(0xFF); tcpClient.Close(); } } ``` 上述例子说明了当面对非常规情况时可以选择更加底层的技术手段如TCP套接字编程来满足具体业务逻辑的要求[^4]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值