zoukankan      html  css  js  c++  java
  • .NET_使用WebService保存图片到某一服务器

    项目需要,两台Web服务器,一台数据库服务器,一台图片服务器,为此需要把图片保存到跟Web服务器不同的另外一台服务器上,所以决定使用WebService的方法。代码如下

    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.IO;

    [WebService(Namespace 
    = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo 
    = WsiProfiles.BasicProfile1_1)]
    public class Service : System.Web.Services.WebService
    {
        
    public Service () {

            
    //如果使用设计的组件,请取消注释以下行 
            
    //InitializeComponent(); 
        }

        [WebMethod(Description 
    = "Web 服务提供的方法,返回是否文件上载成功与否。")]
        
    public bool UploadFile(byte[] fs,string SavePath, string FileName)
        {

            
    string path = System.Configuration.ConfigurationSettings.AppSettings["PicPath"].ToString();
            
    try
            {
                
    //判断类型
                  string picName = FileName;
                
    string fileType = "";
                fileType 
    = picName.Substring(picName.LastIndexOf("."), picName.Length - picName.LastIndexOf(".")).ToLower();
                
    if (fileType != ".jpg" && fileType != ".gif" && fileType != ".bmp")
                {
                    
    return false;
                }

                
    string fullPath = path + "\\" + SavePath;

                
    if (!System.IO.Directory.Exists(fullPath))
                    System.IO.Directory.CreateDirectory(fullPath);


                
    ///定义并实例化一个内存流,以存放提交上来的字节数组。
                  MemoryStream m = new MemoryStream(fs);

                
    ///定义实际文件对象,保存上载的文件。
                  FileStream f = new FileStream(fullPath+"\\" + FileName , FileMode.Create);

                
    ///把内内存里的数据写入物理文件
                  m.WriteTo(f);
                m.Close();
                f.Close();
                f 
    = null;
                m 
    = null;
                
    return true;
            }
            
    catch
            {
                
    return false;
            }
        }

        
    }

    调用方法:

    1.项目先引用该WebService,并命名为picWebService

    2.使用以下代码调用

    HttpPostedFile face = FileUpload.PostedFile;
    picWebService.Service picWebService 
    = new picWebService.Service();
    int upPhotoLength = face.ContentLength;
    byte[] PhotoArray = new Byte[upPhotoLength];
    Stream PhotoStream 
    = face.InputStream;
    PhotoStream.Read(PhotoArray, 
    0, upPhotoLength);
    picWebService.UploadFile(PhotoArray, FilePath, FileName);
    face.InputStream.Close();
  • 相关阅读:
    C#控件开发(三)
    C#控件开发(四)
    如何将方行的按纽改变为其他的形状
    C#绘制圆角矩形
    Win7右键不能新建文件夹
    WinForm窗体FormClosing事件导致无法关机
    反射动态调用WinForm窗口
    C#钩子本线程内消息拦截
    C#控件开发(一)
    七个C#编程小技巧
  • 原文地址:https://www.cnblogs.com/hzsasheng/p/1968161.html
Copyright © 2011-2022 走看看