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('.');
            }
        }

    原文作者:菜鸟de成长历程
    原文地址: https://blog.csdn.net/weixin_44408363/article/details/106178040
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞