一个截图和webapi上传的小栗子

不解释,只是贴贴代码

控制台:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace uploadFile
{
    class Program
    {

        private static Bitmap bitmap = null;
        private static string userName = Environment.MachineName;

        static void Main(string[] args)
        {
            ExecCutScreen();
            Console.ReadLine();
        }

        /// <summary>  
        /// 全屏截图  
        /// </summary>  
        public static void ExecCutScreen()
        {
            bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics gp = Graphics.FromImage(bitmap);
            gp.CopyFromScreen(new Point(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y), new Point(0, 0), bitmap.Size, CopyPixelOperation.SourceCopy);
            try
            {
                string newImg = Guid.NewGuid().ToString(); ;
                //判断图片是否存在,存在将其删除,用新的替代  
                if (File.Exists(newImg))
                {
                    File.Delete(newImg);
                }
                //bitmap.Save("D://"+ newImg, ImageFormat.Png);
                UploadImg(userName, BmpToByte(bitmap));
            }
            catch (Exception ex)
            {
            }
            finally
            {
                gp.Dispose();
                bitmap.Dispose();
            }
        }

        public static void UploadImg(string userName, byte[] fileBytepdf)
        {
            var httpUpload = new HttpUpload();
            httpUpload.SetFieldValue("userName", userName);

            string _apiUrl = "http://localhost:54556/api/UploadFile";

            httpUpload.SetFieldValue("img.png", "img.png", "application/octet-stream", fileBytepdf);
            string responStr = "";
            bool suc = httpUpload.Upload(_apiUrl, out responStr);
            Console.WriteLine(suc);
            Console.ReadLine();
        }


        public static byte[] BmpToByte(Bitmap bitmap)
        {
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] bytes = ms.GetBuffer();
            ms.Close();
            return bytes;
        }
    }
}

HttpUpload类:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace uploadFile
{
    public class HttpUpload
    {
        private ArrayList bytesArray;
        private Encoding encoding = Encoding.UTF8;
        private string boundary = String.Empty;

        public HttpUpload()
        {
            bytesArray = new ArrayList();
            string flag = DateTime.Now.Ticks.ToString("x");
            boundary = "---------------------------" + flag;
        }

        /// <summary>
        /// 合并请求数据
        /// </summary>
        /// <returns></returns>
        private byte[] MergeContent()
        {
            int length = 0;
            int readLength = 0;
            string endBoundary = "--" + boundary + "--\r\n";
            byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);

            bytesArray.Add(endBoundaryBytes);

            foreach (byte[] b in bytesArray)
            {
                length += b.Length;
            }

            byte[] bytes = new byte[length];

            foreach (byte[] b in bytesArray)
            {
                b.CopyTo(bytes, readLength);
                readLength += b.Length;
            }

            return bytes;
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="requestUrl">请求url</param>
        /// <param name="responseText">响应</param>
        /// <returns></returns>
        public bool Upload(String requestUrl, out String responseText)
        {
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);

            byte[] responseBytes;
            byte[] bytes = MergeContent();

            try
            {
                responseBytes = webClient.UploadData(requestUrl, bytes);
                responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                return true;
            }
            catch (WebException ex)
            {
                Stream responseStream = ex.Response.GetResponseStream();
                responseBytes = new byte[ex.Response.ContentLength];
                responseStream.Read(responseBytes, 0, responseBytes.Length);
            }
            responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
            return false;
        }

        /// <summary>
        /// 设置表单数据字段
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        public void SetFieldValue(String fieldName, String fieldValue)
        {
            string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
            string httpRowData = String.Format(httpRow, fieldName, fieldValue);

            bytesArray.Add(encoding.GetBytes(httpRowData));
        }

        /// <summary>
        /// 设置表单文件数据
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="filename">字段值</param>
        /// <param name="contentType">内容内型</param>
        /// <param name="fileBytes">文件字节流</param>
        /// <returns></returns>
        public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
        {
            string end = "\r\n";
            string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string httpRowData = String.Format(httpRow, fieldName, filename, contentType);

            byte[] headerBytes = encoding.GetBytes(httpRowData);
            byte[] endBytes = encoding.GetBytes(end);
            byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];

            headerBytes.CopyTo(fileDataBytes, 0);
            fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
            endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);

            bytesArray.Add(fileDataBytes);
        }
    }
}

WebApi控制器:

       public IHttpActionResult UploadPhoto()
        {
            string userName = HttpContext.Current.Request["userName"];
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (string key in files.AllKeys)
            {
                HttpPostedFile file = files[key];//file.ContentLength文件长度  
                if (string.IsNullOrEmpty(file.FileName) == false)
                {
                    string ext = Path.GetExtension(file.FileName);
                    string newFileName = userName +"_"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
                    string path = HttpContext.Current.Server.MapPath("~/App_Data/CareImg/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    file.SaveAs(path + newFileName);
                }
            }
            return Ok<string>("ok");
        }

猜你喜欢

转载自blog.csdn.net/qq_32688731/article/details/80152503