代码改变世界

WebService传输文件的几个知识点

2014-04-14 20:35  村口王师傅  阅读(2776)  评论(0编辑  收藏  举报

前几天用WebService写了传数据的接口。

要求是 传XML数据 并用Schema(即xsd文件)验证 并且伴有图片传输。

做这个项目首先要理解

WebService 传数据本身是通过XML格式传的,所传的数据最后都被包装在一个XML里了

基于这点,需要准备以下几个知识点。

1. XML Schema 的编写 (命名空间 ,数据类型,定义属性类型,定义多个相同标签方法)

2.用Xsd验证XML的程序代码

3.将文件以什么形式放到xml里

4.如何从xml里取出文件并保存到本地

ps:我用正则声称XML的时候用\1做后向引用不成功,原因是。C#根js一样都用的是类似$1这样引用的,坑爹的教程啊。

好了。我们把几个知识点罗列一下就OK啦。

1.列出XML于XML Schema的样本

      a.xml

<?xml version="1.0" encoding="utf-8" ?>
<!---->
<myxml  xmlns="http://www.aaa.com">
  <!---->

  <Type>01</Type>
  <!--varchar(50), 附件类型 
-->

  <Name></Name>
  <!--varchar(200),附件名称
-->
  <Time></eaTime>
  <!--varchar(50),时间
-->
 

<file fileName=""></file>
 
  <file fileName=""></file>
  <!--varbinary 上传文件
-->
</myxml >

  a.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="EmrAcce"
    targetNamespace="http://www.cnstroke.com"
    elementFormDefault="qualified"
    xmlns="http://www.cnstroke.com"
    xmlns:mstns="http://www.cnstroke.com"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="myxml ">
    <xs:complexType>
      <xs:sequence>

        <xs:element name="Type" type="TypeT"/>

        <xs:element name="Name" type="xs:string"/>
        <xs:element name="Time" type="xs:dateTime"/>
      
        
        <xs:element name="file"  maxOccurs="unbounded" >
          <xs:complexType>
            <xs:attribute name="fileName" type="xs:string"></xs:attribute>
          </xs:complexType>
        </xs:element>
        
      </xs:sequence>
      
    </xs:complexType>
  </xs:element>

  <xs:simpleType name="TypeT">
    <xs:restriction base="xs:string">
      <xs:pattern value="01|02|03|09|10|11|99"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="ClassT">
    <xs:restriction base="xs:string">
      <xs:pattern value="01|02|03|04|99"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="fileNameT">
    <xs:restriction base="xs:string">
      <xs:pattern value=".+[\.]{1,1}.+"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

 2..用Xsd验证XML的程序代码

   private void ValidationEventCallBack(Object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)//区分是警告还是错误
            {
                xmlErr += "<br/>验证成功!警告:" + e.Message;
            }
            else
            {
                xmlErr += "<br/>Err:" + e.Message;
            }
        }
        private void CheckXmlValidate(string strRequestXML)
        {
            string ErrString = string.Empty;
            StringReader sRead = null;
            XmlReader xmlRead = null;
            XmlSchemaSet schemaSet;

            try
            {
                schemaSet = new XmlSchemaSet();

                sRead = new StringReader(strRequestXML);

                schemaSet.Add(null, AppDomain.CurrentDomain.BaseDirectory + "/XML/" + xsdFile + ".xsd");

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventCallBack);
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas = schemaSet;

                xmlRead = XmlReader.Create(sRead, settings);
               // xmlRead = XmlReader.Create(xmlUrl, settings);//此处是通过传路径获取xml
                while (xmlRead.Read())
                {

                }

                if (ErrString.ToString() == String.Empty)
                {

                    xmlErr += "验证成功!";
                }
                else
                {
                    xmlErr += "验证失败!原因可能是:" + ErrString;

                }
            }
            catch (XmlException exec)
            {
                xmlErr += exec.Message;
            }
            finally
            {

                if (xmlRead != null)
                {

                    xmlRead.Close();
                }
            }
        }

3.将文件以什么形式放到xml里

 /// <param name="filePath">相对路径</param>
        /// <param name="fileName"></param>
        protected void setXmlNodeFile(XmlDocument xmldoc, XmlElement xmlelem, string filePath,string fileName)
        {
            XmlElement file = xmldoc.CreateElement("", "file", "");
          
            file.SetAttribute("fileName",fileName);
            string data = null;
            int readByte = 0;        //
            int bytesToRead = 900000;
            FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open);
            bytesToRead = (int)fs.Length;
            BinaryReader br = new BinaryReader(fs);

            byte[] base64buffer = new byte[bytesToRead];
            do
            {
                readByte = br.Read(base64buffer, 0, bytesToRead);      //将数据读入字节数组
                // xmlTxtWt.WriteBase64(base64buffer, 0, readByte);       //将数组中二进制值编码为Base64并写出到XML文件

            } while (bytesToRead <= readByte);
            MemoryStream mem = new MemoryStream(base64buffer);
            data = Convert.ToBase64String(mem.ToArray());
            file.InnerText = data;
            xmlelem.AppendChild(file);
       
        }

4.如何从xml里取出文件并保存到本地

  XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("~/XML/ceshi1.xml"));
            string PicByte = xmldoc.GetElementsByTagName("file")[0].InnerText;
            byte[] b = Convert.FromBase64String(PicByte);
           // System.IO.MemoryStream sm = new MemoryStream();  
           //  sm.Write(b, 0, b.Length);
            using( FileStream fs = new FileStream(Server.MapPath("~/XML/yts.jpg"), FileMode.Create))
            {
           fs.Write(b,0,b.Length);
            }
           return Content("ok");

这样就好了其他细节 就不用说了

-----------------------------------------以下内容摘自网络

1.通过byte传输

把文件转换

  public static byte[] ConvertToBinary(string Path)
 

       {
            FileStream stream = new FileInfo(Path).OpenRead();
            byte[] buffer = new byte[stream.Length];
            Console.WriteLine("The lenght of the file is "+buffer.Length);
            stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
            return buffer;
        }

static byte[] buffer;

buffer = ConvertToBinary(path);

 

webService

  

FileStream fstream = new FileStream(filePath + fileName, FileMode.Append);
        try
        {
            //MemoryStream m = new MemoryStream(fileBt);
            //m.WriteTo(fstream);
            fstream.Write(fileBt, 0, fileBt.Length);   //二进制转换成文件
          
            fstream.Close();
            //rst += "\r\n";
            rst += "File Name is:" + fstream.Name + "\r\n";
            rst += "File Lenght is:" + fstream.Length + "\r\n";
            rst += "File Position is:" + fstream.Position  + "\r\n";
        }
        catch (Exception ex)
        {
            //抛出异常信息
            rst = ex.ToString();
        }
        finally
        {
           
            fstream.Close();
        }