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;
        }





    }
}
复制代码

 

posted @   zh89233  阅读(1346)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示