C#客户端上传图片到远程服务器(单张上传)

  • Post author:
  • Post category:其他




一、连接局域网远程服务器的几种方式




1`webservice 在客户端调用

2`开个ftp在server上 客户端使用ftp命名空间操作上传.

3`服务器开启个socket 客户端连接并且把文件转成byte发过去

4`使用Net Use 通过代码访问已知用户名和密码的局域網服务器文件

5`使用 WebClient 需要输入网络认证


本文使用webservice的方式



二、

编写并使用自定义WebService



http://t.zoukankan.com/gozzl-p-13748009.html    (C# Web Service简介及使用)



图片上传失败时检查一下图片大小,过大会上传失败,在


WebService的web.config中添加



<system.web>

<compilation debug=”true” targetFramework=”4.0″ />

<!–最大请求长度,单位byte,当前限制为1G,超时时间单位为秒,当前时间为1小时–>

<httpRuntime requestValidationMode=”2.0″ maxRequestLength=”1073741824″          executionTimeout=”3600″/>

</system.web>

<system.webServer>

<security>

<requestFiltering>

<!–最大允许请求长度,单位byte,当前限制为1G–>

<requestLimits maxAllowedContentLength=”1073741824″></requestLimits>

</requestFiltering>

</security>

</system.webServer>


using SFC_UpDownFile;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService_UpDownFile
{
    /// <summary>
    ///WebServicefile 的摘要描述
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    
    // 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下列一行。
    // [System.Web.Script.Services.ScriptService]
    public class WebServicefile : System.Web.Services.WebService
    {
        //将Stream流转换为byte数组的方法。
       
        public byte[] ConvertStreamToByteBuffer(Stream s)
        {
            MemoryStream ms = new MemoryStream();
            int b;
            while ((b = s.ReadByte()) != -1)
            {
                ms.WriteByte((byte)b);
            }
            return ms.ToArray();
        }
        //上传文件至WebService所在服务器的方法
        [WebMethod]
        public bool Up(byte[] data, string filename)
        {
            //獲取服務器時間

            DataSet ds = new DataSet();
            ds = SqlHelper.GetDataSet();
            string dateime = DateTime.Parse(Convert.ToString(ds.Tables[0].Rows[0]["datetimes"])).ToString("yyyyMM");

            try
            {
                string path = ConfigurationManager.AppSettings["URL"].ToString() + dateime;
               
                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;
            }
        }
       

        //下载WebService所在服务器上的文件的方法
        [WebMethod]
        public byte[] Down(string filename)
        {
            string filepath = Server.MapPath("File/") + filename;
            if (File.Exists(filepath))
            {
                try
                {
                    FileStream s = File.OpenRead(filepath);
                    return ConvertStreamToByteBuffer(s);
                }
                catch
                {
                    return new byte[0];
                }
            }
            else
            {
                return new byte[0];
            }
        }

    }
}



二、服务器发布

WebService以及程序中调用WebService



http://t.zoukankan.com/gozzl-p-13748009.html    (C# Web Service简介及使用)

注意:必须要添加两个用户名IIS_IUSRS、NETWORK_SERVICE,并添加全部权限,客户端才可以访问服务器上传图片



二、C#程序

调用WebService上传图片

使用FileSystemWatcher的方式监控文件夹中产生的图片

 //定時觸發
public void setInternal2(string PName, string  PPath)
{
   this.timer = new System.Timers.Timer(1000);//实例化Timer类,设置时间间隔   
   timer.Elapsed += new System.Timers.ElapsedEventHandler((s, e) => upload(s, e, 
   PName, PPath));//当到达时间的时候执行事件 
   timer.AutoReset = false;//false是执行一次,true是一直执行
   timer.Enabled = true;//设置是否执行System.Timers.Timer.Elapsed事件 
}

 //圖片監測
 public void PictureWatch()
 {
     string[] filters = { "*.BMP", "*.JPG", "*.PNG" };
     foreach (string f in filters)
     {
       string pathArray = ConfigurationManager.AppSettings["path2"];
       FileSystemWatcher pwc = new FileSystemWatcher();  // 实例化FileSystemWatcher对象
       pwc.Path = pathArray;   //监控的路径
       pwc.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
       NotifyFilters.DirectoryName;
       pwc.Filter = f;   // 监控的新生成的文件格式
       pwc.IncludeSubdirectories = true; // 监控子目录
       pwc.Created += new FileSystemEventHandler(OnCreatedPicture);   // 有圖片创建则触发事件(watch.Created)
       pwc.EnableRaisingEvents = true; // 启动监控
           }
      }
        
     //圖片產生
    private void OnCreatedPicture(object sender, FileSystemEventArgs e)
    {
            string PName = e.Name;
            string PPath = e.FullPath;  
            string dire = PPath.Substring(0, PPath.LastIndexOf("\\") + 1);            
            (sender as FileSystemWatcher).EnableRaisingEvents = false;
            //設置讀取時間
            setInternal2(PName, PPath);        
           (sender as FileSystemWatcher).EnableRaisingEvents = true;
      }
 //圖片上傳
WebReference.WebServicefile up = new WebReference.WebServicefile();                        
FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length);
isup = up.Up(imgBytesIn, name);//name图片的名称
fs.Close();


(记录学习过程)



版权声明:本文为weixin_42151589原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。