ASP.NET Core 上传文件到共享文件夹
参考资料:ASP.NET 上传文件到共享文件夹
创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html
一、配置上传文件相关参数并读取参数
1.配置appsettings.json
{
"FileUploadInfo": {
"UploadPath": "\\\\172.21.0.10\\File",
"DownloadPath": "http://213.10.11.126:8001/",
"UserName": "ShareUser",
"Password": "Password"
}
}
2.读取配置数据
2.1 新建实体类
/// <summary>
/// 文件上传配置项
/// </summary>
public class FileUploadConst
{
/// <summary>
/// 上传地址
/// </summary>
public string UploadPath { get; set; } /// <summary>
/// 文件访问/下载地址
/// </summary>
public string DownloadPath { get; set; } /// <summary>
/// 访问共享目录用户名
/// </summary>
public string UserName { get; set; } /// <summary>
/// 访问共享目录密码
/// </summary>
public string Password { get; set; }
}
2.2 映射实体类与配置项
在startup.cs中配置
public void ConfigureServices(IServiceCollection services)
{
services.Configure<FileUploadConst>(Configuration.GetSection("FileUploadInfo"));
}
3.控制器中读取配置项,通过注入的方式
public FileUploadConst FileUploadConfig { get; set; }
public UploadController(IOptions<FileUploadConst> option)
{
FileUploadConfig = option.Value;
}
二、上传文件
上传文件之前记得初始化构造方法,注入文件上传配置项!!!!!↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
1.连接文件服务器方法
/// <summary>
/// 连接远程共享文件夹
/// </summary>
/// <param name="path">远程共享文件夹的路径</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
private static bool connectState(string path, string userName, string passWord)
{
var flag = false;
var proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
var dosLine = "net use " + path + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
} var errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();if (string.IsNullOrEmpty(errormsg))
{
flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
WriteHelper.WriteFile(ex);
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
} return flag;
}
2.传输文件流到服务器中
/// <summary>
/// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
/// </summary>
/// <param name="inFileStream">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
/// <param name="dst">保存文件的路径,不含名称及扩展名</param>
/// <param name="fileName">保存文件的名称以及扩展名</param>
private static void Transport(Stream inFileStream, string dst, string fileName)
{if (!Directory.Exists(dst))
{
Directory.CreateDirectory(dst);
} dst = dst + fileName; if (!System.IO.File.Exists(dst))
{var outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write); var buf = new byte[inFileStream.Length]; int byteCount; while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush(); inFileStream.Close(); outFileStream.Flush(); outFileStream.Close();
}
}
3.接收文件并上传到文件服务器
/// <summary>
/// 上传附件到文件服务器中
/// </summary>
[HttpPost, Route("api/Upload/UploadAttachment")]
[AllowAnonymous]
public ServiceResponse<UploadRespModel> UploadAttachment()
{
var viewModel = new UploadRespModel();
var code = 200;
var msg = "上传失败!"; var path = FileUploadConfig.UploadPath; //@"\\172.16.10.130\Resource";
var s = connectState(path, FileUploadConfig.UserName, FileUploadConfig.Password);
try
{
if (s)
{
var filelist = HttpContext.Request.Form.Files;
if (filelist.Count > 0)
{
var file = filelist[0];
var fileName = file.FileName;
var blobName = FileHelper.GetSaveFolder(fileName);
path = $@"{path}\{blobName}\"; fileName = $"{DateTime.Now:yyyyMMddHHmmss}{fileName}"; //共享文件夹的目录
var theFolder = new DirectoryInfo(path);
var remotePath = theFolder.ToString();
Transport(file.OpenReadStream(), remotePath, fileName); viewModel.SaveUrl = $"{blobName}/{fileName}";
viewModel.DownloadUrl = GetFileFullPath(viewModel.SaveUrl); msg = "上传成功";
}
}
else
{
code = CommonConst.Code_OprateError;
msg = "链接服务器失败";
}
}
catch (Exception e)
{
Console.WriteLine(e);
msg = e.Message;
} return ServiceResponse<UploadRespModel>.SuccessResponse(msg, viewModel, code);
}
4.图片地址拼接方法
/// <summary>
/// 拼接文件全路径
/// </summary>
/// <param name="filePath">文件相对地址</param>
private string GetFileFullPath(string filePath)
{
var str = string.Empty;
if (!string.IsNullOrEmpty(filePath))
{
// 兼容旧数据
if (filePath.Contains("http://") || filePath.Contains("https://"))
{
str = filePath;
}
else
{
var host = FileUploadConfig.DownloadPath;
str = $"{host}/{filePath}";
}
}
return str;
}
ASP.NET Core 上传文件到共享文件夹的更多相关文章
- ASP.NET 上传文件到共享文件夹
创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html 上传文件代码 web.config <!--上传文件配置,UploadP ...
- .NET CORE上传文件到码云仓库【搭建自己的图床】
.NET CORE上传文件到码云仓库[搭建自己的图床] 先建一个公共仓库(随意提交一个README文件或者.gitignore文件保证master分支的存在),然后到gitee的个人设置页面找到[私人 ...
- .net Core 上传文件详解
.net core 和.net framework上传文件有很多需要注意的地方 .net framework 上传文件用httppostedfilebase .net core 上传文件用 IForm ...
- ASP.NET Core 上传多文件 超简单教程
示例源码下载地址 https://qcloud.coding.net/api/project/3915794/files/4463836/download 项目地址 https://dev.tence ...
- Asp.Net Core WebApi 和Asp.Net WebApi上传文件
public class UpLoadController : ControllerBase { private readonly IHostingEnvironment _hostingEnviro ...
- asp.net 客户端上传文件全路径获取方法
asp.net 获取客户端上传文件全路径方法: eg:F:\test\1.doc 基于浏览器安全问题,浏览器将屏蔽获取客户端文件全路径的方法,只能获取到文件的文件名,如果需要获取全路径则需要另想其他 ...
- ASP.NET MVC上传文件----uploadify的使用
课程设计需要实现上传文件模块,本来ASP.NET是有内置的控件,但是ASP.NET MVC没有,所以就有两种方法:自定义和采用第三方插件.由于时间的关系,故采用第三方插件:uploadify. upl ...
- asp.net 限制上传文件的大小与时间
在web.Config文件中配置限制上传文件大小与时间的字符串是在<httpRuntime><httpRuntime/>节中完成. maxRequsetLength 属性:用于 ...
- ASP.NET MVC上传文件
最近参考网络资料,学习了ASP.NET MVC如何上传文件.最基本的,没有用jQuery等技术. 1.定义Model public class TestModel { [Displ ...
随机推荐
- Ubuntu 16.04 系统基础开发环境搭建
1.安装 Git sudo apt-get update sudo apt-get install git Do you want to continue? [Y/n] Y git --version ...
- 【题解】P3631 [APIO2011]方格染色
很有意思的一道题,所以单独拿出来了. 完整分享看 这里 题目链接 luogu 题意 有一个包含 \(n \times m\) 个方格的表格.要将其中的每个方格都染成红色或蓝色.表格中每个 \(2 \t ...
- 数据结构—— Trie (前缀树)
实现一个 Trie (前缀树),包含 插入, 查询, 和 查询前缀这三个操作. Trie trie = new Trie(); trie.insert("apple"); trie ...
- # spring boot + mybatis 读取数据库
spring boot + mybatis 读取数据库 创建数据库 use testdb; drop table if exists t_city; create table t_city( id i ...
- centos7安装Hive及其问题解决
本地如何安装hive (安装hive之前需要安装hadoop并启动hadoop的相关集群,mysql数据库) hadoop集群是两台,一台作为master,两台作为slaver,mysql单独占用一台 ...
- DRF使用超链接API实现真正RESTful
很多API并不是真正的实现了RESTful,而应该叫做RPC (Remote Procedure Call 远程过程调用),Roy Fielding曾经提到了它们的区别,原文如下: I am gett ...
- ⑦SpringCloud 实战:引入Sleuth组件,完善服务链路跟踪
这是SpringCloud实战系列中第7篇文章,了解前面第两篇文章更有助于更好理解本文内容: ①SpringCloud 实战:引入Eureka组件,完善服务治理 ②SpringCloud 实战:引入F ...
- Phthon几个特殊的函数
Python有几个相对特殊的函数,他们并不会提高工作效率,但是会使代码优雅简洁,其中包括lambda, map, reduce, filter, yeild. 第一:lambda,贴些代码体会. 1 ...
- C# HTML帮助类 包括补全标签 截取HTML字符串包含标签
public static class HtmlHelper { /// <summary> /// 按文本内容长度截取HTML字符串(支持截取带HTML代码样式的字符串) /// < ...
- Autofac官方文档翻译--一、注册组件--3属性和方法注入
官方文档:http://docs.autofac.org/en/latest/register/prop-method-injection.html Autofac 属性和方法注入 虽然构造函数参数注 ...