首页
留言
友链
关于
Search
1
海康威视错误代码大全【完整版】
765 阅读
2
SerialPortStream 稳定易用的第三方串口通信库
311 阅读
3
大华错误代码大全【完整版】
306 阅读
4
iis搭建typecho个人博客
206 阅读
5
typecho中文搜索404解决办法
200 阅读
C#
随笔
SQL
软件
插件
游戏
登录
Search
标签搜索
c#
impinj
文件夹
防火墙
文件上传
typecho
404
.netcore
com
动态编译
语音合成
tcp
having
数据库查重
groupby
监控文件夹
操作文件夹
rsa
加密解密
加密算法
有码挺好
累计撰写
76
篇文章
累计收到
49
条评论
首页
栏目
C#
随笔
SQL
软件
插件
游戏
页面
留言
友链
关于
搜索到
2
篇与
文件上传
的结果
2021-01-19
.netcore大文件上传
.netcore文件上传大致分为两种方式,流式和缓冲式,前者适用于大文件上传,后者则适用于小文件上传,具体区别如下。缓冲:通过模型绑定先把整个文件保存到内存,然后我们通过IFormFile得到stream,优点是效率高,缺点对内存要求大,适用于小文件上传。流式处理:直接读取请求体装载后的Section 对应的stream 直接操作strem即可,无需把整个请求体读入内存;适用于大文件上传。 /// <summary> /// 大文件上传,参数“softPackage”,可自定义 /// </summary> /// <returns></returns> [HttpPost("UploadSoftPackage")] [RequestSizeLimit(419430400)/*文件大小上限,400M,可自定义*/] public async Task<HttpResponseMessage> UploadSoftPackage() { try { //获取boundary var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(Request.ContentType).Boundary).Value ?? ""; //得到reader var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); var webRoot = _hostingEnvironment.WebRootPath/*IWebHostEnvironment,用于获取网站、API根目录*/; bool flag = false; long fileLen = 0; List<string> extList = new List<string>() { ".exe", ".apk", ".zip", ".rar" }; var savePath = string.Empty; //读取section while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (contentDisposition.Name == "softPackage") { var fileName = contentDisposition.FileName.Value; var fileExt = Path.GetExtension(fileName); if (extList.Contains(fileExt)) { flag = true; var dir = Path.Combine(webRoot, "SoftPackage"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } savePath = $"/SoftPackage/{fileName}"; fileLen = await WriteFileAsync(section.Body, Path.Combine(dir, fileName)); } else { return JsonManager.SimpleCustResponse("unsupported media type"); } } } section = await reader.ReadNextSectionAsync(); } if (!flag) { return JsonManager.SimpleCustResponse("softPackage is require"); } else { if (fileLen > 0) { return JsonManager.ReturnSuccessResponse(savePath); } else { return JsonManager.SimpleCustResponse("file upload failed"); } } } catch (Exception ex) { _logger.LogError(ex.ToString()); return JsonManager.SimpleStatusResponse(ResultCode.OPERATE_FAILED); } } /// <summary> /// 写文件导到磁盘 /// </summary> /// <param name="stream">流</param> /// <param name="path">文件保存路径</param> /// <returns></returns> private async Task<int> WriteFileAsync(Stream stream, string path) { const int FILE_WRITE_SIZE = 84975;//写出缓冲区大小 int writeCount = 0; using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, FILE_WRITE_SIZE, true)) { byte[] byteArr = new byte[FILE_WRITE_SIZE]; int readCount = 0; while ((readCount = await stream.ReadAsync(byteArr, 0, byteArr.Length)) > 0) { await fileStream.WriteAsync(byteArr, 0, readCount); writeCount += readCount; } } return writeCount; }
2021年01月19日
65 阅读
0 评论
0 点赞
2021-01-16
.netcore接口附带参数文件上传
因为项目上需要用到文件上传且附带其他参数,需求是有一个winfrom程序要上传文件给netcore webapi 并且上传接口要能够支持多个参数的传递方式;期间也遇到了很多问题,随手记录一下,方便自己也也方便他人。经过实验,采用multipart/form-data的方式可实现带文件、参数;此方法仅适用于小文件上传,大文件上传不建议使用。示例代码首先新建参数接收类 ,类中包含文件与其他参数;参数可自定义,代码如下: public class Snapshot { public string directoy { get; set; } public int type { get; set; } public IFormFile picture { get; set; } public string id { get; set; } }http post图片上传方法,如下代码: [HttpPost("UploadSnaphot")] public async Task<HttpResponseMessage> UploadSnaphot([FromForm] Snapshot snapshot) { return await Task.Run(() => { try { if (snapshot == null) { return JsonManager.SimpleCustResponse("Invalid parameter"); } else if (string.IsNullOrEmpty(snapshot.id)) { return JsonManager.SimpleCustResponse("Invalid parameter warehouseId"); } else if (snapshot.type != 0 && snapshot.type != 1) { return JsonManager.SimpleCustResponse("Invalid parameter type"); } else if (string.IsNullOrEmpty(snapshot.directoy) || !DateTime.TryParseExact(snapshot.directoy, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _dir)) { return JsonManager.SimpleCustResponse("Invalid parameter directoy"); } else if (snapshot.picture == null) { return JsonManager.SimpleCustResponse("Invalid parameter picture"); } else if (snapshot.picture.Length > 1024 * 1024 * 3)//3M { return JsonManager.SimpleCustResponse("file size too big"); } else { //判断图片扩展名是否正确 List<string> extList = new List<string>() { ".png", ".jpg" }; var ext = Path.GetExtension(snapshot.picture.FileName).ToLower(); if (!extList.Contains(ext)) { return JsonManager.SimpleCustResponse("unsupport media type"); } else { using (MemoryStream ms = new MemoryStream()) { //拷贝文件到内存流 snapshot.picture.CopyTo(ms); var tmp = ms.GetBuffer(); var fileType = tmp[0].ToString() + tmp[1].ToString(); //通过判断文件头类型判断是否图片格式,13780 png,255216 jpg if (fileType == "13780" || fileType == "255216") { var _path = “{_hostingEnvironment.WebRootPath}\\SnapPic\\TestUpload\\{snapshot.id.Replace("-", "")}\\{snapshot.directoy}"; if (!Directory.Exists(_path)) { Directory.CreateDirectory(_path); } Bitmap.FromStream(ms).Save([ DISCUZ_CODE_1 ]quot;{_path}\\{snapshot.picture.FileName}"); return JsonManager.SimpleStatusResponse(ResultCode.OPERATE_SUCCESS); } else { return JsonManager.SimpleCustResponse("unsupport media type"); } } } } } catch (Exception ex) { //_logger.LogError(ex.ToString()); return JsonManager.SimpleCustResponse("unsupport media type"); } }); }
2021年01月16日
73 阅读
0 评论
1 点赞