故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

.net core上传图片,文件。webapi 上传图片文件

10694人阅读 2019/3/30 11:51 总访问:3842462 评论:0 收藏:0 手机
分类: .NET Core

上传图片的前台代码都完全一样,直接来贴后台的代码吧

 public ActionResult UploadImage(List<IFormFile> upfile)
        {

            //Request.Form.Files["file"]也可以通过这样的方式获取文件
            if (upfile == null)
            {
                return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = "文件资源为空" };
            }

            //获取静态资源文件根目录
            string webRootPath = _hostingEnvironment.WebRootPath;

            foreach (var formFile in upfile)
            {
                if (formFile.Length > 0)
                {

                    string fileExt = formFile.FileName.Substring(formFile.FileName.LastIndexOf('.')); //文件扩展名
                    long fileSize = formFile.Length; //获得文件大小,以字节为单位

                    if (fileSize > 1024 * 1024 * 2) //2M
                    {
                        //上传的文件不能大于2M
                    }

                    string newFileName = System.Guid.NewGuid().ToString("N") + fileExt; //随机生成新的文件名
                    var filePath = webRootPath + "/arcimg/" + newFileName;//上传文件的完整目录
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                        stream.Flush();
                    }
                }
            }

            return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = "上传图片成功" };
        }

这里有个net core中获取项目根目录的物理路径问题:

具体可以参考:

http://www.tnblog.net/aojiancc2/article/details/2347


说一下两点注意:

1:net core中没有saveas,所有不能使用saveas这个方法来上传图片

     而是通过一个文件流来上传,最重要的就是formFile.CopyTo(stream)了;


2:upfile这个就是对应前台文件选择框的name


3:  图片存放的地址,不要随便新建一个文件夹去存储,那样是访问不到的!!!!,应该放到那个wwwroot

     文件夹里边去,那个是官方推荐的存储静态资源的位置,例如js,css,图片等文件

     所以可以在哪里去创建一个文件夹

     


.net core webapi 上传图片文件基本也差不多,前端一般使用vue类似的技术栈
测试代码如下:

/// <summary>
///  上传多个文件
/// </summary>
/// <param name="Files"></param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public string Post(IFormCollection Files)
{
    try
    {
        string dd = Files["File"];
        var form = Files;//定义接收类型的参数
        Hashtable hash = new Hashtable();
        IFormFileCollection cols = Request.Form.Files;
        if (cols == null || cols.Count == 0)
        {
            return "没有上传文件";
        }
        foreach (IFormFile file in cols)
        {
            //定义图片数组后缀格式
            string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
            //获取图片后缀是否存在数组中
            string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
            if (LimitPictureType.Contains(currentPictureExtension))
            {
                //这里暂时不重新生成文件名称,图片重命名使用guid或者时间都可以
                // var new_path = DateTime.Now.ToString("yyyyMMdd")+ file.FileName;
                var new_path = Path.Combine("uploads/images/", file.FileName);
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", new_path);
                //这步之前最好做一下文件夹是否存在的判断,如果不存在就创建一下
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                    stream.Flush();
                }
            }
            else
            {
                return "请上传指定格式的图片";
            }
        }
        return "上传成功";
    }
    catch (Exception ex)
    {
        return "上传失败";
    }
}




欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价