zoukankan      html  css  js  c++  java
  • 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;
            }
    
    
    
    
    
        }
    }
  • 相关阅读:
    codeforces 1438D,思路非常非常巧妙的构造题
    【Azure DevOps系列】开始第一个Azure DevOps应用
    .NET Core SameSite cookie问题
    解决Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    feign.FeignException$NotFound: status 404 reading OrdersClient#isBuyCourse(String,String)
    feign.FeignException$NotFound: status 404 reading EduClient#getCourseInfoOrder
    谷粒学院查询全部课程不显示问题
    解决java.sql.SQLException: Zero date value prohibited
    使用Visual Studio Code代码编辑器给vue安装插件,结果导致node_modules里面的安装好的依赖丢失
    Redis报错: Caused by: io.lettuce.core.RedisConnectionException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, ...
  • 原文地址:https://www.cnblogs.com/love-zf/p/6049177.html
Copyright © 2011-2022 走看看