总结一下.net core的上传文件操作,这里主要分上传到本地的也就是MVC的,另一种是上传到WebAPi的.

一、Web端

1.新建一个.net core mvc项目

2.这里的版本是.net core 2.2.4

3.新建一个控制器 TestController

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; namespace Web.Controllers
{
public class TestController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public TestController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
return View();
} /// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
[HttpPost]
public string UploadFiles(string z)
{
long size = ;
var path = "";
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
string fileExt = Path.GetExtension(file.FileName); //文件扩展名
long fileSize = file.Length; //获得文件大小,以字节为单位
string newFileName = System.Guid.NewGuid().ToString() + fileExt; //随机生成新的文件名
path = "/upload/" + newFileName;
path = _hostingEnvironment.WebRootPath + $@"\{path}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(path))
{
file.CopyTo(fs);
fs.Flush();
}
path = "/upload/" + newFileName;
}
return path;
} }
}

4.新建页面Index

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="form0">
<input type="file" name="file" />
<input type="button" value="上传本地" onclick="upload()" />
</form>
</body>
</html>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/jquery.form.js"></script>
<script>
function upload() {
var formData = new FormData($("#form0")[]);
$.ajax({
url: "/test/UploadFiles",
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'post',
success: function (d) {
console.log(d);
}
})
} </script>

5.注意:默认所有的静态文件都放在wwwroot 所以这里我在wwwroot下创建了文件夹upload从来存储文件

这样Web端的上传文件就搞定了

二、WebApi端

1.新建一个webapi项目

2.新建一个api控制器 TestApiController

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json; namespace WebApi.Controllers
{
[EnableCors("AllowSameDomain")]//跨域
[Route("api/[controller]/[action]")]
[ApiController]
public class TestApiController : ControllerBase
{
private readonly IHostingEnvironment _hostingEnvironment; public TestApiController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
} [HttpPost]
public ResultObject UploadIForm(List<IFormFile> files)
{
List<String> filenames = new List<string>(); foreach (var file in files)
{
var fileName = file.FileName;
Console.WriteLine(fileName); fileName = $"/UploadFile/{fileName}";
filenames.Add(fileName); fileName = _hostingEnvironment.WebRootPath + fileName; using (FileStream fs = System.IO.File.Create(fileName))
{
file.CopyTo(fs);
fs.Flush();
}
} return new ResultObject
{
state = "Success",
resultObject = filenames
};
}
[HttpPost]
public string Upload(IFormCollection Files)
{ try
{
//var form = Request.Form;//直接从表单里面获取文件名不需要参数
string dd = Files["File"];
var form = Files;//定义接收类型的参数
Hashtable hash = new Hashtable();
IFormFileCollection cols = Request.Form.Files;
if (cols == null || cols.Count == )
{
return JsonConvert.SerializeObject(new { status = -, message = "没有上传文件", data = hash });
}
foreach (IFormFile file in cols)
{
//定义图片数组后缀格式
string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
//获取图片后缀是否存在数组中
string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
if (LimitPictureType.Contains(currentPictureExtension))
{ //为了查看图片就不在重新生成文件名称了
// 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))
{ //图片路径保存到数据库里面去
bool flage = true;
if (flage == true)
{
//再把文件保存的文件夹中
file.CopyTo(stream);
hash.Add("file", "/" + new_path);
}
}
}
else
{
return JsonConvert.SerializeObject(new { status = -, message = "请上传指定格式的图片", data = hash });
}
} return JsonConvert.SerializeObject(new { status = , message = "上传成功", data = hash });
}
catch (Exception ex)
{ return JsonConvert.SerializeObject(new { status = -, message = "上传失败", data = ex.Message });
} } }
public class ResultObject
{
public String state { get; set; }
public Object resultObject { get; set; }
} }

3.这里前台页面还是通过ajax来请求api的,所以就需要进行跨域

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//允许一个或多个具体来源:
services.AddCors(options =>
{
// Policy 名稱 CorsPolicy 是自訂的,可以自己改
//跨域规则的名称
options.AddPolicy("AllowSameDomain", policy =>
{
// 設定允許跨域的來源,有多個的話可以用 `,` 隔開
policy
.WithOrigins("http://127.0.0.1:53189", "http://localhost:53189")
//.AllowAnyOrigin()//允许所有来源的主机访问
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();//指定处理cookie
});
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowSameDomain");//必须位于UserMvc之前
app.UseMvc();
}
}
}

4.前台页面 还是用这个方法,url改下

function upload1() {
var formData = new FormData($("#form0")[]);
$.ajax({
url: "http://127.0.0.1:8067/api/testapi/Upload",
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'post',
success: function (d) {
console.log(d); }
})
}

5.将webapi发布到iis

6.同样的,静态文件还是在wwwroot下,api发布后是没有wwwroot文件夹的,所以直接建 /wwwroot/upload文件夹

这样上传就搞定了

.net core2.2上传文件总结的更多相关文章

  1. IE8/9 JQuery.Ajax 上传文件无效

    IE8/9 JQuery.Ajax 上传文件有两个限制: 使用 JQuery.Ajax 无法上传文件(因为无法使用 FormData,FormData 是 HTML5 的一个特性,IE8/9 不支持) ...

  2. 三种上传文件不刷新页面的方法讨论:iframe/FormData/FileReader

    发请求有两种方式,一种是用ajax,另一种是用form提交,默认的form提交如果不做处理的话,会使页面重定向.以一个简单的demo做说明: html如下所示,请求的路径action为"up ...

  3. asp.net mvc 上传文件

    转至:http://www.cnblogs.com/fonour/p/ajaxFileUpload.html 0.下载 http://files.cnblogs.com/files/fonour/aj ...

  4. app端上传文件至服务器后台,web端上传文件存储到服务器

    1.android前端发送服务器请求 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空) <!-- <bean id="multipartResolver&q ...

  5. .net FTP上传文件

    FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...

  6. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  7. 前端之web上传文件的方式

    前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构造请求上传文件 1. web上传 ...

  8. Django session cookie 上传文件、详解

    session 在这里先说session 配置URL from django.conf.urls import patterns, include, url from django.contrib i ...

  9. 4 django系列之HTML通过form标签来同时提交表单内容与上传文件

    preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...

随机推荐

  1. Redux action 状态

    action  不同的状态,设置不同的action.type [就是一个名字],返回对应的数据 不同的状态返回不同的  接口数据

  2. [学习笔记]Pollard-Rho

    之前学的都是假的 %%zzt Miller_Rabin:Miller-Rabin与二次探测 大质数分解: 找到所有质因子,再logn搞出质因子的次数 方法:不断找到一个约数d,递归d,n/d进行分解, ...

  3. linux Tasklets 机制

    tasklet 类似内核定时器在某些方面. 它们一直在中断时间运行, 它们一直运行在调度它 们的同一个 CPU 上, 并且它们接收一个 unsigned long 参数. 不象内核定时器, 但是, 你 ...

  4. CodeForces - 375D Tree and Queries (莫队+dfs序+树状数组)

    You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will ass ...

  5. E40笔记本无线网卡

    E40笔记本无线网卡详情 网卡名称 Intel(R) Dual Band Wireless-AC 3160 网卡厂商 英特尔 Mac地址 34:E6:AD: 规格 - 基本要素 状态 Launched ...

  6. Kafka2.4发布——新特性介绍(附Java Api Demo代码)

    新功能 允许消费者从最近的副本进行获取 为 Consumer Rebalance Protocol 增加对增量协同重新均衡(incremental cooperative rebalancing)的支 ...

  7. appium启动app(android)

    android ​ Appium 启动APP至少需要5个参数 ​ 'platformVersion','deviceName'.'appPackage'.'appActivity'.'platform ...

  8. mysql主从之Mysql_mysql基本安装

    下载安装包: https://dev.mysql.com/downloads/mysql/5.7.html#downloads [root@jenkins-master ~]# cd /usr/loc ...

  9. c++ 基础知识回顾 继承 继承的本质就是数据的copy

    c++ 基础知识笔记 继承 什么是继承 继承就是子类继承父类的成员属性以及方法 继承的本质就是 数据的复制 是编译器帮我们做了很多操作 class Base { public: Base(){ cou ...

  10. $HDU$ 4336 $Card\ Collector$ 概率$dp$/$Min-Max$容斥

    正解:期望 解题报告: 传送门! 先放下题意,,,已知有总共有$n$张卡片,每次有$p_i$的概率抽到第$i$张卡,求买所有卡的期望次数 $umm$看到期望自然而然想$dp$? 再一看,哇,$n\le ...