转载 :通过Web Services上传和下载文件

本文介绍如何使用 Web Services 在客户端与服务器间上传和下载二进制文件。通过 GetBinaryFile Web 服务,实现了文件字节数组的获取及文件类型的返回功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContractedBlock.gifExpandedBlockStart.gifCode
通过Web Services上传和下载文件 
随着Internet技术的发展和跨平台需求的日益增加,Web Services的应用越来越广,我们不但需要通过Web Services传递字符串信息,而且需要传递二进制文件信息。下面,我们就分别介绍如何通过Web Services从服务器下载文件到客户端和从客户端通过Web Services上载文件到服务器。

一:通过Web Services显示和下载文件

我们这里建立的Web Services的名称为GetBinaryFile,提供两个公共方法:分别是GetImage()和GetImageType(),前者返回二进制文件字节数组,后者返回文件类型,其中,GetImage()方法有一个参数,用来在客户端选择要显示或下载的文件名字。这里我们所显示和下载的文件可以不在虚拟目录下,采用这个方法的好处是:可以根据权限对文件进行显示和下载控制,从下面的方法我们可以看出,实际的文件位置并没有在虚拟目录下,因此可以更好地对文件进行权限控制,这在对安全性有比较高的情况下特别有用。这个功能在以前的ASP程序中可以用Stream对象实现。为了方便读者进行测试,这里列出了全部的源代码,并在源代码里进行介绍和注释。

首先,建立GetBinaryFile.asmx文件:

我们可以在VS.net里新建一个C#的aspxWebCS工程,然后“添加新项”,选择“Web服务”,并设定文件名为:GetBinaryFile.asmx,在“查看代码”中输入以下代码,即:GetBinaryFile.asmx.cs:

    
using System;
    
using System.Collections;
    
using System.ComponentModel;
    
using System.Data;
    
using System.Diagnostics;
    
using System.Web;
    
using System.Web.UI;
    
using System.Web.Services;
    
using System.IO;

    
namespace <a href="http://dev.21tx.com/dotnet/xml/" target="_blank">XML</a>.sz.luohuedu<a href="http://dev.21tx.com/dotnet/" target="_blank">.net</a>.aspxWebCS
    {
        
/// <summary>
        
/// GetBinaryFile 的摘要说明。
        
/// Web Services名称:GetBinaryFile
        
/// 功能:返回服务器上的一个文件对象的二进制字节数组。
        
/// </summary>
    [<a href="http://dev.21tx.com/dotnet/webservice/" target="_blank">WebService</a>(Namespace="http://<a href="http://dev.21tx.com/web/xml/" target="_blank">XML</a>.sz.luohuedu.net/",
        Description="在Web Services里利用.NET框架进行传递二进制文件。")]
        
public class GetBinaryFile : System.Web.Services.WebService
        {

            
#region Component Designer generated code
            
//Web 服务设计器所必需的
            private IContainer components = null;

            
/// <summary>
            
/// 清理所有正在使用的资源。
            
/// </summary>
            protected override void Dispose( bool disposing )
            {
                
if(disposing && components != null)
                {
                    components.Dispose();
                }
                
base.Dispose(disposing);
            }

            
#endregion

       
public class Images: System.Web.Services.WebService
     {
       
/// <summary>
       
/// Web 服务提供的方法,返回给定文件的字节数组。
       
/// </summary>
       [WebMethod(Description="Web 服务提供的方法,返回给定文件的字节数组")]
       
public byte[] GetImage(string requestFileName)
       {
       
///得到服务器端的一个图片
       
///如果你自己测试,注意修改下面的实际物理路径
       if(requestFileName == null || requestFileName == "")
         
return getBinaryFile("D:\\Picture.JPG");
       
else
         
return getBinaryFile("D:\\" + requestFileName);
       }

       
/// <summary>
       
/// getBinaryFile:返回所给文件路径的字节数组。
       
/// </summary>
       
/// <param name="filename"></param>
       
/// <returns></returns>
       public byte[] getBinaryFile(string filename)
       {
       
if(File.Exists(filename))
       {
         
try
         {
         
///打开现有文件以进行读取。
         FileStream s = File.OpenRead(filename);
         
return ConvertStreamToByteBuffer(s);
         }
         
catch(Exception e)
         {
         
return new byte[0];
         }
       }
       
else
       {
         
return new byte[0];
       }
       }
     
/// <summary>
     
/// ConvertStreamToByteBuffer:把给定的文件流转换为二进制字节数组。
     
/// </summary>
     
/// <param name="theStream"></param>
     
/// <returns></returns>
       public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
       {
       
int b1;
       System.IO.MemoryStream tempStream 
= new System.IO.MemoryStream();
       
while((b1=theStream.ReadByte())!=-1)
       {
         tempStream.WriteByte(((
byte)b1));
       }
       
return tempStream.ToArray();
       }
       [WebMethod(Description
="Web 服务提供的方法,返回给定文件类型。")]
       
public string GetImageType()
       {
         
///这里只是测试,您可以根据实际的文件类型进行动态输出
         return "image/jpg";
       }
     }
    }
    }

一旦我们创建了上面的asmx文件,进行编译后,我们就可以编写客户端的代码来进行调用这个Web Services了。

我们先“添加Web引用”,输入:http:
//localhost/aspxWebCS/GetBinaryFile.asmx。下面,我们编写显示文件的中间文件:GetBinaryFileShow.aspx,这里,我们只需要在后代码里编写代码即可,GetBinaryFileShow.aspx.cs文件内容如下:

    
using System;
    
using System.Collections;
    
using System.ComponentModel;
    
using System.Data;
    
using System.Drawing;
    
using System.Web;
    
using System.Web.SessionState;
    
using System.Web.UI;
    
using System.Web.UI.<a href="http://dev.21tx.com/dotnet/aspnet/webcontrols/" target="_blank">WebControls</a>;
    
using System.Web.UI.HtmlControls;
    
using System.Web.Services;

    
namespace aspxWebCS
    {
        
/// <summary>
        
/// GetBinaryFileShow 的摘要说明。
        
/// </summary>
        public class GetBinaryFileShow : System.Web.UI.Page
        {

            
private void Page_Load(object sender, System.EventArgs e)
            {
            
// 在此处放置用户代码以初始化页面
           ///定义并初始化文件对象;
           xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images oImage;
           oImage 
= new xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();
           
///得到二进制文件字节数组;
           byte[] image = oImage.GetImage("");
           
///转换为支持存储区为内存的流
           System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);
           
///定义并实例化Bitmap对象
           Bitmap bm = new Bitmap(memStream);
           
///根据不同的条件进行输出或者下载;
           Response.Clear();
           
///如果请求字符串指定下载,就下载该文件;
           
///否则,就显示在浏览器中。
           if(Request.QueryString["Download"]=="1")
           {
           Response.Buffer 
= true;
           Response.ContentType 
= "application/octet-stream";
           
///这里下载输出的文件名字 ok.jpg 为例子,你实际中可以根据情况动态决定。
           Response.AddHeader("Content-Disposition","attachment;filename=ok.jpg");
           }
           
else
           Response.ContentType 
= oImage.GetImageType();
           Response.BinaryWrite(image);
           Response.End();
            }

            
#region Web Form Designer generated code
            
override protected void OnInit(EventArgs e)
            {
                
//
                
// CODEGEN:该调用是 <a href="http://dev.21tx.com/dotnet/aspnet/" target="_blank">ASP.NET</a> Web 窗体设计器所必需的。
                
//
                InitializeComponent();
                
base.OnInit(e);
            }

            
/// <summary>
            
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
            
/// 此方法的内容。
            
/// </summary>
            private void InitializeComponent()
            {
       
this.Load += new System.EventHandler(this.Page_Load);

     }
            
#endregion
        }
    }

最后,我们就编写最终的浏览页面:GetBinaryFile.aspx,这个文件很简单,只需要aspx文件即可,内容如下:

    
<%@ Page language="c#" Codebehind="GetBinaryFile.aspx.cs" AutoEventWireup="false"
     Inherits
="aspxWebCS.GetBinaryFile" %>
    
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    
<HTML>
     
<HEAD>
       
<title>通过Web Services显示和下载文件</title>
       
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
       
<meta name="CODE_LANGUAGE" Content="C#">
       
<meta name="vs_defaultClientScript" content="<a href="http://dev.21tx.com/web/javascript/" target="_blank">JavaScript</a>">
       <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
     
</HEAD>
     
<body MS_POSITIONING="GridLayout">
       
<form id="GetBinaryFile" method="post" runat="server">
         
<FONT face="宋体">
           
<asp:HyperLink id="HyperLink1" NavigateUrl="GetBinaryFileShow.aspx?Download=1"
             runat
="server">下载文件</asp:HyperLink>
           
<br/>
           
<!--下面是直接显示文件-->
           
<asp:Image id="Image1" ImageUrl="GetBinaryFileShow.aspx" runat="server"></asp:Image>
         
</FONT>
       
</form>
     
</body>
    
</HTML> 

转载于:https://www.cnblogs.com/z2002m/archive/2009/07/11/1521357.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值