123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Http;
- using XdCxRhDw.Dto;
- namespace XdCxRhDW.WebApi.Controllers
- {
- /// <summary>
- ///文件上传接口
- /// </summary>
- public class FileController : BaseController
- {
- private readonly string uploadFolder;
-
- /// <summary>
- ///
- /// </summary>
- public FileController()
- {
- this.uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
- }
- /// <summary>
- /// 上传文件
- /// </summary>
- /// <returns></returns>
- [HttpPost, SwaggerForm]
- public async Task<AjaxResult<FileUploadResDto>> UploadFileAsync()
- {
- if (!Request.Content.IsMimeMultipartContent("form-data"))
- {
- bool s=Request.Content.IsFormData();
- return Error<FileUploadResDto>("请求数据不是form-data类型");
- }
- var provider = new MultipartMemoryStreamProvider();
- await Request.Content.ReadAsMultipartAsync(provider);
- Directory.CreateDirectory(uploadFolder);
- var content = provider.Contents.First();
- var fileName = Guid.NewGuid().ToString() + ".dat";
- var fileData = await content.ReadAsByteArrayAsync();
- FileUploadResDto fileDto = new FileUploadResDto();
- fileDto.FileName = fileName;
- // 将文件保存到本地文件夹中
- var filePath = Path.Combine(uploadFolder, fileName);
- using (var fileStream = new FileStream(filePath, FileMode.Create))
- {
- await fileStream.WriteAsync(fileData, 0, fileData.Length);
- }
- //清除1个小时之前的文件
- _ = Task.Run(() => {
- var files=Directory.EnumerateFiles(uploadFolder);
- foreach (var file in files)
- {
- FileInfo info=new FileInfo(file);
- if (info.CreationTime<DateTime.Now.AddHours(-1))
- {
- try
- {
- info.Delete();
- }
- catch
- {
- }
- }
- }
- });
- return Success(fileDto);
- }
- }
- }
|