.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();

 

 

posted @ 2011-03-01 17:13  不爱啰嗦的胜哥  阅读(1033)  评论(0编辑  收藏  举报