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();
  • 相关阅读:
    Linux下几种文件传输命令 sz rz sftp scp
    jqGrid subGrid配置 如何首次加载动态展开所有的子表格
    MySQL使用规范
    Navicat连接MySQL报错2059
    微信小程序
    完美解决 ios10 及以上 Safari 无法禁止缩放的问题
    html5利用getObjectURL获取图片路径上传图片
    Vue的单页应用中如何引用单独的样式文件
    用JS添加和删除class类名
    APP中的 H5和原生页面如何分辨、何时使用
  • 原文地址:https://www.cnblogs.com/hzsasheng/p/1968161.html
Copyright © 2011-2022 走看看