xxqyzsc 发表于 2015-5-21 08:06:46

win8平板App-文件上传

  private StorageFile _storageFile;
  ///
      /// 上传文件
      ///
      ///
      ///
      public async Task UpLoad(string url)
      {
            try
            {
                //读取文件流
                Stream _stream = await _storageFile.OpenStreamForReadAsync();
                //
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers["Accept-Encoding"] = "gzip";
                request.Headers["Cache-Control"] = "no-cache";
                request.Headers["UserAgent"] = "Mozilla/5.0 (compatible; MSIE10.0; Trident/5.0; IEMobile/9.0; Microsoft Corporation)";               
                request.AllowReadStreamBuffering = false;
                request.ContinueTimeout = 3000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                  Stream requestStream = await request.GetRequestStreamAsync();
                #region 生成流
                  //头部连字符
                string header = "--";
                //换行符
                string lineBreak = "\r\n";
                var boundary = string.Concat(header, Function.GenerateRndNonce());
                request.ContentType = string.Concat("multipart/form-data; boundary=", boundary);
                using (var ms = new MemoryStream())
                {
                  byte[] boundaryData = Encoding.UTF8.GetBytes(lineBreak + header + boundary + lineBreak);
                    #region 写入文件数据
                  string fileData = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineBreak + "Content-Type: {2}" + lineBreak + lineBreak;
                    string item = string.Format(fileData, "File", _storageFile.Name, FileOperate.GetContentType(_storageFile.Name));
                  byte[] data = Encoding.UTF8.GetBytes(item);
                  ms.Write(boundaryData, 0, boundaryData.Length);
                  ms.Write(data, 0, data.Length);
                  FileOperate.WriteTo(ms, await _storageFile.OpenAsync(FileAccessMode.Read));
                  #endregion
                    //写入结束线
                  boundaryData = Encoding.UTF8.GetBytes(lineBreak + header + boundary + header + lineBreak);
                  ms.Write(boundaryData, 0, boundaryData.Length);
                  ms.WriteTo(requestStream);
                  requestStream.Dispose();
                }
                #endregion
  using (WebResponse response = await request.GetResponseAsync())
                {
                  Stream _streamNew=response.GetResponseStream();
                   dynamic root = new DataContractJsonSerializer(typeof(ApiFormResult)).ReadObject(_streamNew) as ApiFormResult;
                   return root;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            
      }
  ==============================================
  以下是文件操作和随机数生成的方法:
  internal class FileOperate
    {
      public static readonly string[] Document = new string[] { ".doc", ".xls", ".ppt", ".docx", ".xlsx", ".pptx", ".pdf", ".txt", ".rtf",".zip",".rar" };
      public static readonly string[] Image    = new string[] { ".jpg", ".png", ".bmp", ".gif", ".tif" };
      public static readonly string[] Music = new string[] { ".mp3", ".wma", ".m4a", ".aac" };
      
      ///
      /// 根据文件扩展名获取文件类型
      ///
      /// 文件名
      ///
      public static string GetContentType(string fileName)
      {
            var fileExt = System.IO.Path.GetExtension(fileName);
            return GetCommonFileContentType(fileExt);
      }
      ///
      /// 获取通用文件的文件类型
      ///
      /// 文件扩展名.如".jpg",".gif"等
      ///
      private static string GetCommonFileContentType(string fileExt)
      {
            switch (fileExt)
            {
                case ".jpg":
                case ".jpeg":
                  return "image/jpeg";
                case ".gif":
                  return "image/gif";
                case ".bmp":
                  return "image/bmp";
                case ".png":
                  return "image/png";
                default:
                  return "application/octet-stream";
            }
      }
      ///
      /// 将当前的文件数据写入到某个数据流中
      ///
      ///
      public static void WriteTo(Stream stream,IRandomAccessStream randomAccessStream)
      {
            byte[] buffer = new byte;
            int size = 0;
  if (randomAccessStream != null)
            {
                //写入文件流
                while ((size = randomAccessStream.AsStreamForRead().Read(buffer, 0, buffer.Length)) > 0)
                {
                  stream.Write(buffer, 0, size);
                }
            }
      }
    }
    internal class Function
    {
      ///
      /// 随机种子
      ///
      private static Random RndSeed = new Random();
      ///
      /// 生成一个随机码
      ///
      ///
      public static string GenerateRndNonce()
      {
            return string.Concat(
            RndSeed.Next(1, 99999999).ToString("00000000"),
            RndSeed.Next(1, 99999999).ToString("00000000"),
            RndSeed.Next(1, 99999999).ToString("00000000"),
            RndSeed.Next(1, 99999999).ToString("00000000"));
      }
    }
  
页: [1]
查看完整版本: win8平板App-文件上传