C# 模拟POST上传图片至服务器

2016年7月16日 0 作者 snowysong@live.com
阅读需要3分钟

0x00.添加引用

using System;
using System.IO;
using System.Net.Http.Headers;
using System.ComponentModel;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Imaging;

 


0x01.选择文件

        List<UploadImageInfo> imginfo = new List<UploadImageInfo>();
        private async void SelectFiles_Click(object sender, RoutedEventArgs e)
        {          
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            var files = await openPicker.PickMultipleFilesAsync();//选择多个文件

            foreach (StorageFile sf in files)
            {
                tokenInfo = await TokenInfo.GetTokenAsync();//自定义获取token函数
                UploadImageInfo uploadImages = new UploadImageInfo();//自定义图片类
                BitmapImage bitmap = new BitmapImage();
                using (var stream = await sf.OpenAsync(FileAccessMode.ReadWrite))
                {
                    bitmap.SetSource(stream);
                    if (stream.Size < 1024 * 1024)
                    {
                        uploadImages.DataSize = Math.Round((double)stream.Size / 1024, 2).ToString ()+"  Kb";
                    }
                    else
                    {
                        uploadImages.DataSize = Math.Round((double)stream.Size / 1024 / 1024, 2).ToString()+"  Mb";
                    }
                    Stream s = WindowsRuntimeStreamExtensions.AsStreamForRead(stream.GetInputStreamAt(0));
                    uploadImages.ContentByte = ConvertStreamTobyte(s);
                    s.Close();//务必结束,否则文件会一直被占用。
                }

                uploadImages.Content = bitmap;
                uploadImages.Name = sf.Name;
                uploadImages.DateCreated = sf.DateCreated.ToString();
                uploadImages.Cameras = cameras;
                uploadImages.Lens = lens;
                imginfo.Add(uploadImages);
}

0x02.异步上传

public static async Task<string> UploadFilesAsync(UploadImageInfo uploadImageInfo, string uzrtoken, string uploadtoken, string userId, string campaignId)
{
   HttpClientHandler handler = new HttpClientHandler();
   HttpClient httpClient = new HttpClient(Sign.HttpClientHandler);
   httpClient.DefaultRequestHeaders.Accept.ParseAdd("text/*");
   httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("Shockwave Flash");

   HttpResponseMessage response = new HttpResponseMessage();
   var content = new MultipartFormDataContent();//使用MultipartFormDataContent进行form-data请求头封装
   var contentByteContent = new ByteArrayContent(uploadImageInfo.ContentByte);
   contentByteContent.Headers.Add("Content-Type", "application/octet-stream");
   contentByteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
   contentByteContent.Headers.ContentDisposition.FileName = "\"" + uploadImageInfo.Name + "\"";
   contentByteContent.Headers.ContentDisposition.Name = "\"imagefile\"";//封装POST请求头
    {
      content.Add(new StringContent(uploadImageInfo.Name), "\"Filename\"");
      content.Add(new StringContent("1"), "\"uploadTokenType\"");
      content.Add(new StringContent("0"), "\"fileType\"");
      content.Add(new StringContent(uploadImageInfo.Name), "\"title\"");
      content.Add(new StringContent("2"), "\"userTokenType\"");
      content.Add(new StringContent(campaignId), "\"campaignId\"");
      content.Add(new StringContent(userId), "\"userId\"");
      content.Add(new StringContent(uploadtoken), "\"uploadToken\"");
      content.Add(new StringContent(uzrtoken), "\"userToken\"");
      content.Add(contentByteContent, "\"imagefile\"");
      content.Add(new StringContent("Submit Query"), "\"Upload\"");
    }

   response = await httpClient.PostAsync(new Uri("http://media.sony.com.cn/alphacafe/upload", UriKind.Absolute), content);
   string sid = response.Content.ReadAsStringAsync().Result;
   
   if (response.IsSuccessStatusCode&&sid.Contains("fileID")==true)
    {
      string s = response.Content.ReadAsStringAsync().Result.Split('"')[7];
      return s;
    }
   else return "failed";
}



0x03.上传

private async void Submit_Click(object sender, RoutedEventArgs e)
{
  foreach (UploadImageInfo item in imgitems)
   {
    string fileId = await UploadImageInfo.UploadFilesAsync(item, tokenInfo.userToken, tokenInfo.upLoadToken, userId, "16");
    if (fileId.Contains("failed") == false)
     {
      item.FileID.Insert(0, fileId);//上传成功则返回文件Id
     }
   }
}

 

0 0 vote
Article Rating