webapi上次文件

2021-02-21 02:19

阅读:554

 

//控制器

[HttpPost]
[Route("image/uploads")]
public async Task Uploads()
{
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new FileUploadException("请求的数据格式不正确");
}
var paths = await _uploader.Upload(Request.Content);
if (!paths.Any())
{
throw new FileUploadException("上传失败");
}
return paths;
}
[HttpPost]
[Route("image/uploadOss")]
public async Task UploadOss()
{
var httpRequest = HttpContext.Current.Request;
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new FileUploadException("请求的数据格式不正确");
}
var paths = await _uploader.PutObjectFromFile(httpRequest);

if (!paths.Any())
{
throw new FileUploadException("上传失败");
}
return paths.First();
}

 

//api 接口

public async Task Upload(HttpContent content)
{
//文件存储地址
string dirPath = BaseDirectory + RelativePath;
if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);

// 采用MultipartMemoryStreamProvider
var provider = new CustomMultipartFormDataStreamProvider(dirPath);
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await content.ReadAsMultipartAsync(provider);
var savePaths = provider.FileData.Select(p => RelativePath + Path.GetFileName(p.LocalFileName)).ToArray();
//对已保存的文件进行处理
var resultPaths = FileHandler(savePaths).Select(p => ServerHost + p).ToArray();

return resultPaths;
}
catch { return new string[] { }; }
}

///


/// 上传文件到阿里云oss
///

///
///
public async Task PutObjectFromFile(HttpRequest content)
{
try
{
var pahts = new List();
if (content.Files.Count foreach (string file in content.Files)
{
var postedFile = content.Files[file];
var path = RelativePath + DateTime.Now.ToString("yyyyMMddHHmmssfff")+"."+ postedFile.FileName.Split(‘.‘)[1];
client.PutObject(BucketName, path, postedFile.InputStream);
pahts.Add(Path.Combine("http://cczc-static.oss-cn-beijing.aliyuncs.com/", path));
}
return pahts.ToArray();
}
catch { return new string[] { }; }
}

//参数配置

protected static readonly string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
protected static readonly string ServerHost = ConfigurationManager.AppSettings["ServerHost"];
protected static readonly string BucketName = ConfigurationManager.AppSettings["BucketName"];

///


/// 文件上传相对路径,子类可重写
///

///
protected virtual string RelativePath { get; } = $"upload/image/{DateTime.Today:yyyyMM/dd}/";

protected static string Endpoint { get; } = “你的阿里云访问域名”

protected static string AccessKeyId { get; } = AccessKeyId ;

protected static string AccessKeySecret { get; } = AccessKeySecret;

protected static OssClient client = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);


评论


亲,登录后才可以留言!