.net core 上传文件到本地服务器

2023-10-31 13:42:51 浏览数 (1)

1、本文是上传文件到本地服务器,主要以作者做的业务上传apk为例子,下面直接上代码

代码语言:c#复制
[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) // 如果不存在就创建file文件夹
        {
            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是新建控制器类时继承了基类,基类内包含如下方法

代码语言:c#复制
/// <summary>
/// 返回成功信息
/// </summary>
/// <param name="data">附加内容</param>
/// <param name="msg">成功信息</param>
/// <returns>返回Result格式信息</returns>
[NonAction]
public IActionResult SuccessResult(object data = null, string msg = "成功")
{
    return ToJsonContent(new Result < object > ()
    {
        Code = 200,
        Msg = msg,
        Data = data == null ? new {} : data
    });
}
 
/// <summary>
/// 返回错误信息
/// </summary>
/// <param name="msg">错误信息</param>
/// <param name="code">错误码</param>
/// <param name="statusCode">HTTP状态代码的值,未登录和登录过期为HttpStatusCode.Unauthorized,没有权限是HttpStatusCode.Forbidden</param>
/// <returns>返回Result格式信息</returns>
[NonAction]
public IActionResult ErrorResult(string msg, int code, HttpStatusCode statusCode = HttpStatusCode.OK)
{
    return ToJsonContent(new Result < object > ()
    {
        Code = code,
        Msg = msg,
    });
}
 
/// <summary>
/// JSON格式转换
/// </summary>
/// <param name="obj"></param>
/// <param name="isNull"></param>
/// <returns></returns>
[NonAction]
public IActionResult ToJsonContent(object obj, bool isNull = false)
{
    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        WriteIndented = true, //格式化json字符串
            AllowTrailingCommas = true, //可以结尾有逗号
            IgnoreNullValues = isNull, //可以有空值,转换json去除空值属性
            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 上传文件到本地服务器的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

0 人点赞