zoukankan      html  css  js  c++  java
  • C# webApi上传图片 代码篇

    十年河东,十年河西,莫欺少年穷

    学无止境,精益求精

    代码篇,不多说

    如下:

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Web.Http;
    
    namespace FileUp.Controllers
    {
        public class FileController : ApiController
        {
            [HttpPost]
            public async Task<string> UploadFileStream()
            {
                string returns = string.Empty;
                string fileType = "ss";//要创建的子文件夹的名字
                var uploadPath = "~/upload";
                string filePath = System.Web.HttpContext.Current.Server.MapPath(uploadPath + "/" + fileType + "/");//绝对路径
                //string filePath = uploadPath + "\" + fileType + "\";  //E:Fileup  居家
                if (Directory.Exists(filePath) == false) 
                {
                    Directory.CreateDirectory(filePath);
                }
    
                try
                {
                    var provider = new ReNameMultipartFormDataStreamProvider(filePath);
    
                    await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o =>
                    {
    
                        foreach (var file in provider.FileData)
                        {
                            string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');//待上传的文件名
                            FileInfo fileinfo = new FileInfo(file.LocalFileName);
                            //判断开始
                            int maxSize = 10000000;
                            string oldName = orfilename;//选择的文件的名称
                            if (fileinfo.Length <= 0)
                            {
                                //文件大小判断 未选择上传的图片 大小为零
                            }
                            else if (fileinfo.Length > maxSize)
                            {
                                //文件大小判断 上传文件是否超限制
                            }
                            else
                            {
                                //
                                string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                                string Extension = fileExt;
                                string CreateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
    
                                //定义允许上传的文件扩展名 
                                String fileTypes = "gif,jpg,jpeg,png,bmp";
                                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                                {
    
                                    returns = "上传的文件格式不是图片";
                                }
                                else
                                {
                                    returns = string.Format(@"/Uploads/{0}/{1}", fileType, System.IO.Path.GetFileName(file.LocalFileName));
                                }
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    returns = ex.ToString();
                }
                return returns;
            }
    
            /// <summary>
            /// 重命名上传的文件
            /// </summary>
            public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
            {
                public ReNameMultipartFormDataStreamProvider(string root)
                    : base(root)
                { }
    
                public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
                {
    
                    string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
                    return Guid.NewGuid().ToString().Replace("-", "") + extension;
                }
    
                private string GetValidFileName(string filePath)
                {
                    char[] invalids = System.IO.Path.GetInvalidFileNameChars();
                    return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
                }
    
            }
        }
    }
    View Code

    PostMan请求如下:

    @陈卧龙的博客

  • 相关阅读:
    Windows下搭建HTK
    使用VS2012遇到的问题
    Chapter 3:Speech Production and Perception
    Chapter2:Discrete-Time Signal Processing and Short-Time Fourier Analysis
    Chapter 1:Introduction
    将SVM用于多类分类
    Kernel ridge regression(KRR)
    Sklearn学习笔记
    LDA与QDA
    〖Linux〗使用ssh登录远程主机,并在本地打开远程图形界面
  • 原文地址:https://www.cnblogs.com/chenwolong/p/Uplode.html
Copyright © 2011-2022 走看看