当前位置:首页 > 行业动态 > 正文

c#怎么把图片上传到服务器上

C#实现图片上传到服务器的方法:使用WebClient类的UploadFile方法或通过HttpClient发送POST请求并包含图片数据。

在C#中把图片上传到服务器上,通常可以采用以下几种常见的方法:

c#怎么把图片上传到服务器上  第1张

1、使用WebClient类

示例代码

 using System;
     using System.Collections.Generic;
     using System.Drawing;
     using System.IO;
     using System.Net;
     using System.Text;
     class Program
     {
         static void Main(string[] args)
         {
             string serverUrl = "http://yourserver.com/upload"; // 服务器上传接口地址
             string filePath = @"C:pathtoyourimage.jpg"; // 本地图片路径
             string result = UploadImage(serverUrl, filePath);
             Console.WriteLine(result);
         }
         static string UploadImage(string serverUrl, string filePath)
         {
             try
             {
                 WebClient client = new WebClient();
                 client.Headers[HttpRequestHeader.ContentType] = "image/jpeg"; // 根据图片类型设置ContentType
                 byte[] responseArray = client.UploadFile(serverUrl, "POST", filePath);
                 return Encoding.ASCII.GetString(responseArray);
             }
             catch (Exception ex)
             {
                 return "Error: " + ex.Message;
             }
         }
     }

代码解释:首先创建WebClient对象,然后设置请求头中的ContentType为图片的类型(这里以image/jpeg为例),接着使用UploadFile方法将图片文件以POST方式上传到服务器指定接口,最后将服务器返回的响应转换为字符串并返回。

2、使用HttpWebRequest类

示例代码

 using System;
     using System.IO;
     using System.Net;
     using System.Text;
     class Program
     {
         static void Main(string[] args)
         {
             string serverUrl = "http://yourserver.com/upload"; // 服务器上传接口地址
             string filePath = @"C:pathtoyourimage.jpg"; // 本地图片路径
             string result = UploadImage(serverUrl, filePath);
             Console.WriteLine(result);
         }
         static string UploadImage(string serverUrl, string filePath)
         {
             try
             {
                 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                 byte[] buffer = new byte[fs.Length];
                 fs.Read(buffer, 0, buffer.Length);
                 fs.Close();
                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
                 request.Method = "POST";
                 request.ContentType = "image/jpeg"; // 根据图片类型设置ContentType
                 request.ContentLength = buffer.Length;
                 using (Stream requestStream = request.GetRequestStream())
                 {
                     requestStream.Write(buffer, 0, buffer.Length);
                 }
                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                 {
                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                     {
                         return reader.ReadToEnd();
                     }
                 }
             }
             catch (Exception ex)
             {
                 return "Error: " + ex.Message;
             }
         }
     }

代码解释:先通过FileStream读取本地图片文件的内容到字节数组buffer中,然后创建HttpWebRequest对象并设置请求方法为POST、ContentType和ContentLength等属性,接着将字节数组写入请求流中发送到服务器,最后从响应流中读取服务器返回的结果并返回。

3、通过WebService上传

示例代码

 using System;
     using System.Collections.Generic;
     using System.Data;
     using System.IO;
     using System.Linq;
     using System.Net;
     using System.Text;
     using System.Xml.Serialization;
     using SFC_UpDownFile;
     using System.Configuration;
     using System.Web.Services;
     namespace WebService_UpDownFile
     {
         public class UpLoadController : System.Web.Services.WebService
         {
             // 定义存储文件夹
             private string SavePath
             {
                 get
                 {
                     return "/Register/";
                 }
             }
             // 上传文件至WebService所在服务器的方法
             [WebMethod]
             public bool Up(byte[] data, string filename)
             {
                 try
                 {
                     string path = ConfigurationManager.AppSettings["URL"].ToString() + DateTime.Now.ToString("yyyyMM");
                     if (!Directory.Exists(path))
                     {
                         Directory.CreateDirectory(path);
                     }
                     FileStream fs = File.Create(path + "\" + filename);
                     fs.Write(data, 0, data.Length);
                     fs.Close();
                     return true;
                 }
                 catch
                 {
                     return false;
                 }
             }
         }
     }

客户端调用示例代码

 using System;
     using System.Collections.Generic;
     using System.IO;
     using System.Net;
     using System.Text;
     using System.Xml.Serialization;
     class Program
     {
         static void Main(string[] args)
         {
             string serverUrl = "http://yourserver.com/WebService_UpDownFile/UpLoadController.asmx"; // WebService地址
             string filePath = @"C:pathtoyourimage.jpg"; // 本地图片路径
             string result = UploadImage(serverUrl, filePath);
             Console.WriteLine(result);
         }
         static string UploadImage(string serverUrl, string filePath)
         {
             try
             {
                 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                 byte[] buffer = new byte[fs.Length];
                 fs.Read(buffer, 0, buffer.Length);
                 fs.Close();
                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl + "/Up?filename=image.jpg"); // 注意修改此处的参数名和方法名与WebService中一致
                 request.Method = "POST";
                 request.ContentType = "application/octet-stream"; // 对于二进制数据,一般使用该ContentType
                 request.ContentLength = buffer.Length;
                 using (Stream requestStream = request.GetRequestStream())
                 {
                     requestStream.Write(buffer, 0, buffer.Length);
                 }
                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                 {
                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                     {
                         return reader.ReadToEnd();
                     }
                 }
             }
             catch (Exception ex)
             {
                 return "Error: " + ex.Message;
             }
         }
     }

代码解释:首先在服务器端创建一个WebService,其中包含一个用于上传文件的方法Up,然后在客户端,通过HttpWebRequest向该WebService的上传方法发送请求,将图片文件的字节数据作为请求体发送过去,并获取服务器返回的结果。

4、使用第三方库(如Flurl)

示例代码

 using Flurl; // 引用Flurl库,可通过NuGet安装:Install-Package Flurl
     using Flurl.Http; // 引用Flurl.Http库,可通过NuGet安装:Install-Package Flurl.Http
     using System;
     using System.IO;
     using System.Threading.Tasks;
     class Program
     {
         static async Task Main(string[] args)
         {
             string serverUrl = "http://yourserver.com/upload"; // 服务器上传接口地址
             string filePath = @"C:pathtoyourimage.jpg"; // 本地图片路径
             string result = await UploadImageAsync(serverUrl, filePath);
             Console.WriteLine(result);
         }
         static async Task<string> UploadImageAsync(string serverUrl, string filePath)
         {
             try
             {
                 var response = await filePath.UploadAsync(new Uri(serverUrl), "image/jpeg"); // 根据图片类型设置ContentType,这里以jpeg为例
                 return await response.Content.ReadAsStringAsync(); // 读取服务器返回的结果并返回
             }
             catch (Exception ex)
             {
                 return "Error: " + ex.Message;
             }
         }
     }

代码解释:使用Flurl库简化HTTP请求的操作,通过filePath.UploadAsync方法将本地图片文件上传到服务器指定接口,该方法会自动处理文件的读取和请求的发送,最后读取服务器返回的结果并返回。

0