c#图片上传和文件上传Api接口

1.图片上传

       Random rd = new Random();
        #region 图片上传

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="type">projectPhoto 项目图片 projectRecordPhoto 项目大事记图片 shot 随手拍图片 shotSafe 安全检查图片</param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadPhoto")]
        [Description("图片上传")]
        public async Task<HttpResponseMessage> UploadPhoto(string type = "")
        {
            try
            {
                string guid = Guid.NewGuid().ToString(); ;
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = "/Upload/" + type;
                string uploadFolderPath = HostingEnvironment.MapPath(root);

                string path = uploadFolderPath + guid;

                //如果路径不存在,创建路径
                if (!Directory.Exists(uploadFolderPath))
                {
                    Directory.CreateDirectory(uploadFolderPath);
                }

                List<string> files = new List<string>();
                var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, guid);

                try
                {
                    // Read the form data.
                    await Request.Content.ReadAsMultipartAsync(provider);
                    foreach (var file in provider.FileData)
                    {
                        //接收文件                 
                        files.Add(root + "/" + Path.GetFileName(file.LocalFileName));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("上传图片错误;" + ex.ToString());
                    return ReturnMessageObj("");
                }
                return ReturnMessageObj(string.Join(",", files));
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("上传图片错误;" + ex.ToString());
                return ReturnMessageObj("");
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="type">projectFile 项目文件</param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFile")]
        [Description("文件上传")]
        public async Task<HttpResponseMessage> UploadFile(string type = "")
        {
            try
            {
                string guid = Guid.NewGuid().ToString(); ;
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = "/Upload/" + type;
                string uploadFolderPath = HostingEnvironment.MapPath(root);

                string path = uploadFolderPath + guid;

                //如果路径不存在,创建路径
                if (!Directory.Exists(uploadFolderPath))
                {
                    Directory.CreateDirectory(uploadFolderPath);
                }

                List<string> files = new List<string>();
                var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, guid);

                try
                {
                    // Read the form data.
                    await Request.Content.ReadAsMultipartAsync(provider);
                    foreach (var file in provider.FileData)
                    {
                        //接收文件                 
                        files.Add(root + "/" + Path.GetFileName(file.LocalFileName));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("上传文件错误;" + ex.ToString());
                    return ReturnMessageObj("");
                }
                return ReturnMessageObj(string.Join(",", files));
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("上传图片错误" + ex.ToString());
                return ReturnMessageObj("");
            }
        }


        /// <summary>
        /// 图片上传批量图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadPhoto2")]
        [Description("图片上传2号")]
        public async Task<HttpResponseMessage> UploadPhotoBatch()
        {
            try
            {
                //string guid = Guid.NewGuid().ToString();
                //判断有没有图片
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                string root = "/Upload/";
                //获取项目运行位置
                string uploadFolderPath = HostingEnvironment.MapPath(root);
                //如果路径不存在,创建路径
                if (!Directory.Exists(uploadFolderPath))
                {
                    Directory.CreateDirectory(uploadFolderPath);
                }
                List<string> files = new List<string>();
                //上传图片处理类
                var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, "");

                try
                {
                    // Read the form data.
                    //把图片保存在文件夹
                    await Request.Content.ReadAsMultipartAsync(provider);
                    //返回地址
                    foreach (var file in provider.FileData)
                    {
                        //接收文件                 
                        files.Add(root + "/" + Path.GetFileName(file.LocalFileName));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("上传图片错误;" + ex.ToString());
                    return ReturnMessageObj("");
                }
                return ReturnMessageObj(string.Join(",", files));
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("上传图片错误;" + ex.ToString());
                return ReturnMessageObj("");
            }
        }



        /// <summary>
        /// 上传图片处理
        /// </summary>
        public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public string guid { get; set; }

            public WithExtensionMultipartFormDataStreamProvider(string rootPath, string guidStr) : base(rootPath)
            {
                guid = guidStr;
            }
            public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
            {
                string fileName = string.IsNullOrEmpty(guid) ? headers.ContentDisposition.Name.Replace("\"", "") : guid;
                string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
                string fileName2 = fileName;
                int i = 2;
                while (File.Exists(HostingEnvironment.MapPath("/Upload/" + fileName2 + extension)))
                {
                    fileName2 = fileName + "_$" + i;
                    i++;
                }
                return fileName2 + extension;
            }
            private string GetValidFileName(string filePath)
            {
                char[] invalids = System.IO.Path.GetInvalidFileNameChars();
                return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值