1、本文是上传文件到本地服务器,主要以作者做的业务上传apk为例子,下面直接上代码
[HttpGet, HttpPost, HttpOptions]
[Consumes("application/json", "multipart/form-data")]
public IActionResult UploadFileToServer([FromForm] IFormCollection file)
{
try
{
IFormFile item = null;
if(file.IsNull() || file.Count <= 0)
{
var files = Request.Form.Files;;
if(files.Count <= 0)
{
return ErrorResult("未获取到上传文件,请重新上传", 111111);
}
item = files[0];
}
var filename = string.Empty;
var Folder = AppDomain.CurrentDomain.BaseDirectory + "AppFileUploads/";
if(Directory.Exists(Folder) == false)
{
Directory.CreateDirectory(Folder);
}
item = file.Files[0];
if(item == null)
{
return ErrorResult("文件内容为空,请重新上传", 111112);
}
string name = item.FileName;
string pathName = Path.GetExtension(name);
if(pathName != ".apk")
{
return ErrorResult("不支持该文件格式,请上传APK后缀文件", 111113);
}
filename = Folder + name;
if(System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
using(FileStream fs = System.IO.File.Create(filename))
{
item.CopyTo(fs);
fs.Flush();
}
return SuccessResult(filename, "文件上传到本地服务器成功!");
}
catch(Exception ex)
{
return ErrorResult("上传文件到本地服务器出现异常,异常原因为:" + ex.Message, 111150);
}
}
2、关于返回值SuccessResult、ErrorResult是新建控制器类时继承了基类,基类内包含如下方法
[NonAction]
public IActionResult SuccessResult(object data = null, string msg = "成功")
{
return ToJsonContent(new Result < object > ()
{
Code = 200,
Msg = msg,
Data = data == null ? new {
} : data
});
}
[NonAction]
public IActionResult ErrorResult(string msg, int code, HttpStatusCode statusCode = HttpStatusCode.OK)
{
return ToJsonContent(new Result < object > ()
{
Code = code,
Msg = msg,
});
}
[NonAction]
public IActionResult ToJsonContent(object obj, bool isNull = false)
{
JsonSerializerOptions options = new JsonSerializerOptions()
{
WriteIndented = true,
AllowTrailingCommas = true,
IgnoreNullValues = isNull,
IgnoreReadOnlyProperties = true,
PropertyNameCaseInsensitive = true,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};
options.Converters.Add(new DateTimeJsonConverter());
return Content(JsonSerializer.Serialize(obj, options));
}
以上就是.net core 上传文件到本地服务器的介绍,做此记录,如有帮助,欢迎点赞关注收藏!