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

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于C# .NET Core的WebAPI上传文件接口示例: ```csharp [ApiController] [Route("[controller]")] public class FileUploadController : ControllerBase { private readonly ILogger<FileUploadController> _logger; public FileUploadController(ILogger<FileUploadController> logger) { _logger = logger; } [HttpPost] public async Task<IActionResult> Upload(IFormFile file) { try { if (file == null || file.Length == 0) return Content("file not selected"); var filePath = Path.Combine(Path.GetTempPath(), file.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return Ok(); } catch (Exception ex) { _logger.LogError(ex, "Error uploading file"); return StatusCode(500); } } } ``` 以上代码实现了一个简单的文件上传接口,接收一个名为“file”的文件参数,将其保存到临时目录中。 下面是一个.NET Core调用示例: ```csharp public async Task UploadFile(string filePath) { using (var httpClient = new HttpClient()) { using (var form = new MultipartFormDataContent()) { using (var stream = new FileStream(filePath, FileMode.Open)) { using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); var byteArrayContent = new ByteArrayContent(memoryStream.ToArray()); form.Add(byteArrayContent, "file", Path.GetFileName(filePath)); using (var response = await httpClient.PostAsync("http://localhost:5000/FileUpload", form)) { response.EnsureSuccessStatusCode(); } } } } } } ``` 以上代码使用HttpClient将文件上传WebAPI接口,其中“http://localhost:5000/FileUpload”是WebAPI的URL地址。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值