首页 > 代码库 > web api 处理发送过来的文件(图片)

web api 处理发送过来的文件(图片)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using fastJSON;
using System.IO;
using System.Net.Http;
using DoMain;
using System.Web.Configuration;

namespace PreAlert_WebService.Controllers
{
    public class Article_Pic_Controller : ApiController
    {
        /// <summary>
        /// 增加图片服务
        /// </summary>
        /// <param name="jsonParames"></param>
        /// <returns></returns>
        [HttpPost, HttpGet]
        public string Pic_Add(string jsonParames)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
            }

            HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");

            int maxRequestLength = (runTime.MaxRequestLength) * 1024;
            int len = System.Web.HttpContext.Current.Request.ContentLength;
            string retJsonStr = "";
            if (string.IsNullOrEmpty(jsonParames) || jsonParames.ToLower() == "jsonparames")
            {

                jsonParames = System.Web.HttpContext.Current.Request.Form["jsonParames"];

            }

            IDictionary<string, object> entityDic = (Dictionary<string, object>)JSON.Instance.Parse(jsonParames);

            string guid = Guid.NewGuid().ToString();//图片唯一ID
            //string app_path = AppDomain.CurrentDomain.BaseDirectory;
            string app_path = System.Configuration.ConfigurationManager.AppSettings["app_path"];
            string[] needParames = { "PicType", "PicSizeByte" };
            //IDictionary<string, object> entityDic = (Dictionary<string, object>)JSON.Instance.Parse(jsonParames);
            foreach (string needParame in needParames)
            {
                if (!entityDic.ContainsKey(needParame))
                {
                    retJsonStr = "{\"ret\":\"0\",\"msg\":\"缺少必须的参数:" + needParame + "}";
                    return retJsonStr;
                }
            }
            //默认png图片格式...
            string PicType = entityDic["PicType"].ToString().Trim() != "" ? entityDic["PicType"].ToString() : "png";
            string Description = entityDic["Description"].ToString();
            string PicPath = "/articlepic/" + CollectItemID.ToString();
            string PicDir = app_path + PicPath;
            string FullPath = PicDir + "/" + guid + "." + PicType;

            int PicSizeByte = 0;
            int.TryParse(entityDic["PicSizeByte"].ToString(), out PicSizeByte);

            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection fileCollection = request.Files;

            // 判断是否有文件
            if (fileCollection.Count > 0)
            {
                // 获取图片文件
                HttpPostedFile httpPostedFile = fileCollection[0];
                // 文件扩展名
                string fileExtension = Path.GetExtension(httpPostedFile.FileName);
                // 验证图片格式
                if (fileExtension.Contains(".jpg") || fileExtension.Contains(".png") || fileExtension.Contains(".bmp") || fileExtension.Contains(".gif"))
                {
                    // 如果目录不存在则要先创建
                    if (!Directory.Exists(PicDir))
                    {
                        Directory.CreateDirectory(PicDir);
                    }
                    httpPostedFile.SaveAs(FullPath);
                    using (DBEntities db = new DBEntities())
                    {
                        Pic apic = new Pic();

                        apic.PicPath = PicPath + "/" + guid + "." + PicType;
                        apic.PicType = PicType;
                        apic.PicSizeByte = PicSizeByte;
                        db.Pic.Add(apic);
                        db.SaveChanges();
                    }
                    retJsonStr = "{\"ret\":\"1\",\"msg\":创建成功\"}";
                    return retJsonStr;
                }
                else
                {
                    retJsonStr = "{\"ret\":\"0\",\"msg\":请选择jpg/png/bmp/gif格式的图片\"}";
                }
            }
            else
            {
                retJsonStr = "{\"ret\":\"0\",\"msg\":图片传输错误:没有发现要上传的图片;\"}";
            }

            retJsonStr = "{\"ret\":\"1\",\"msg\":创建成功\"}";
            return retJsonStr;
        }





    }
}

 

web api 处理发送过来的文件(图片)