润宇软件
首 页 企业简介 项目案例 软件定制 行业软件 解决方案 企业动态 服务专区 客服中心
业务介绍:西安软件公司、软件开发、软件定制、软件外包
软件 方案 文章
  润宇软件 >> 新闻资讯  >> 解决方案

西安软件开发中跨服务器通过Web Service来上传文件

发布时间:2022/8/15  浏览次数:次  字体【    】
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.IO;
 
namespace UpDownFile
{
    /**/
    /// <summary>
    /// UpDownFile 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class UpDownFile : System.Web.Services.WebService
    {
        //上传文件至WebService所在服务器的方法,这里为了操作方法,文件都保存在UpDownFile服务所在文件夹下的File目录中
        [WebMethod]
        public bool Up(byte[] data, string filename)
        {
            try
            {
                FileStream fs = File.Create(Server.MapPath("File/") + 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];
            }
        }
    }
}
上传:
 

            //FileUpload1是aspx页面的一个FileUpload控件
            UpDownFile.UpDownFile up = new UpDownFile.UpDownFile();
            up.Up(ConvertStreamToByteBuffer(FileUpload1.PostedFile.InputStream),
            FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\\") + 1));

下载:
            UpDownFile.UpDownFile down = new UpDownFile.UpDownFile();
            byte[] file = down.Down(Request.QueryString["filename"].ToString()); //filename是要下载的文件路径,可自行以其它方式获取文件路径
            Response.BinaryWrite(file);

以下是将文件流转换成文件字节的函数(因为Stream类型的是不能直接通过WebService传输):

 protected byte[] ConvertStreamToByteBuffer(Stream s)
 {
    BinaryReader br = new BinaryReader(stream);
    byte[] fileBytes = br.ReadBytes((int)stream.Length);
    return fileBytes;
}
  关闭本页
西部IT网合作伙伴 合作伙伴
陕西省 | 榆林 | 延安 | 铜川 | 渭南 | 商洛 | 宝鸡 | 汉中 | 安康 | 咸阳
网站首页 | 关于我们 | 售后服务 | 项目合同 | 查看留言 | 在线留言 | 客服中心
© 版权所有:西安润宇软件科技有限公司 
公司地址:西安市丝路国际创意梦工厂4号楼 联系电话:029-87878512 手机:13468700578 联系人:李先生
Copyright ® 2009-2020 RunYusoft.com Inc. All Rights Reserved 
技术支持:西安润宇软件科技有限公司  陕ICP备11000720号