win8平板App-文件上传

 private StorageFile _storageFile;

/// <summary>
/// 上传文件
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public async Task<object> 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" };

/// <summary>
/// 根据文件扩展名获取文件类型
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static string GetContentType(string fileName)
{
var fileExt = System.IO.Path.GetExtension(fileName);
return GetCommonFileContentType(fileExt);
}
/// <summary>
/// 获取通用文件的文件类型
/// </summary>
/// <param name="fileExt">文件扩展名.如".jpg",".gif"等</param>
/// <returns></returns>
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";
}
}
/// <summary>
/// 将当前的文件数据写入到某个数据流中
/// </summary>
/// <param name="stream"></param>
public static void WriteTo(Stream stream,IRandomAccessStream randomAccessStream)
{
byte[] buffer = new byte[512];
int size = 0;

if (randomAccessStream != null)
{
//写入文件流
while ((size = randomAccessStream.AsStreamForRead().Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, size);
}
}
}
}
internal class Function
{
/// <summary>
/// 随机种子
/// </summary>
private static Random RndSeed = new Random();
/// <summary>
/// 生成一个随机码
/// </summary>
/// <returns></returns>
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"));
}
}

 

posted @ 2012-11-07 15:22  xiaofoyuan  阅读(1121)  评论(0编辑  收藏  举报