.net core2.2上传文件总结
总结一下.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上传文件总结的更多相关文章
- IE8/9 JQuery.Ajax 上传文件无效
IE8/9 JQuery.Ajax 上传文件有两个限制: 使用 JQuery.Ajax 无法上传文件(因为无法使用 FormData,FormData 是 HTML5 的一个特性,IE8/9 不支持) ...
- 三种上传文件不刷新页面的方法讨论:iframe/FormData/FileReader
发请求有两种方式,一种是用ajax,另一种是用form提交,默认的form提交如果不做处理的话,会使页面重定向.以一个简单的demo做说明: html如下所示,请求的路径action为"up ...
- asp.net mvc 上传文件
转至:http://www.cnblogs.com/fonour/p/ajaxFileUpload.html 0.下载 http://files.cnblogs.com/files/fonour/aj ...
- app端上传文件至服务器后台,web端上传文件存储到服务器
1.android前端发送服务器请求 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空) <!-- <bean id="multipartResolver&q ...
- .net FTP上传文件
FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...
- 通过cmd完成FTP上传文件操作
一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...
- 前端之web上传文件的方式
前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构造请求上传文件 1. web上传 ...
- Django session cookie 上传文件、详解
session 在这里先说session 配置URL from django.conf.urls import patterns, include, url from django.contrib i ...
- 4 django系列之HTML通过form标签来同时提交表单内容与上传文件
preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...
随机推荐
- React 简书
create-react-app jianshu yarn add styled-components -D 利用js写css样式 样式会更高效 https://github.com ...
- Java发送邮件Demo
就是个Demo,有使用Spring的东西 package xxxxxxx.common.utils; import org.springframework.mail.javamail.JavaMail ...
- 从http到https--phpStudy2018
0. 将SSL证书解压到以下目录,申请方式见 百度 Apache/cert/ 分别更名为 my_public.crt my.key my_chain.crt 1. phpStudy->其它选项菜 ...
- javascript基础之循环
//while循环 <script type="text/javascript"> i = 1; while (i <= 6) { document.write( ...
- LightOJ - 1284 Lights inside 3D Grid (概率计算)
题面: You are given a 3D grid, which has dimensions X, Y and Z. Each of the X x Y x Z cells contains a ...
- dotnet 通过 WMI 获取系统安装的驱动
本文告诉大家如何通过 WMI 获取用户已经安装的驱动程序 通过 Win32_SystemDriver 可以获取用户已经安装的驱动程序 var mc = "Win32_SystemDriver ...
- Elasticsearch搜索调优
最近把搜索后端从AWS cloudsearch迁到了AWS ES和自建ES集群.测试发现search latency高于之前的benchmark,可见模拟数据远不如真实数据来的实在.这次在产线的bac ...
- 什么是神经网络 (Neural Network)
反向传播: 可以看作是再一次将传过来的信号传回去, 看看这个负责传递信号神经元对于”讨糖”的动作到底有没有贡献, 让它好好反思与改正, 争取下次做出更好的贡献. 生物神经网络和人工神经网络的差别: 人 ...
- MySQL性能优化:MySQL中的隐式转换造成的索引失效
数据库优化是一个任重而道远的任务,想要做优化必须深入理解数据库的各种特性.在开发过程中我们经常会遇到一些原因很简单但造成的后果却很严重的疑难杂症,这类问题往往还不容易定位,排查费时费力最后发现是一个很 ...
- IntelliJ IDEA+springboot+jdbctemplet+easyui+maven+oracle搭建简易开发框架(一)
前言: 这两天为了巩固easyui的各个控件用法,搭建了一个简易的框架用于开发,大家可以用来参考,如果发现文章中有哪些不正确不合理的地方,也请各位不吝赐教,感激不尽.文章最下面有源码,可以用于参考.整 ...