linux部署.net core api并且实现上传图片

为了体验.net在linux上运行,所以使用HttpClient东借西抄做了一个简单的api上传功能。

第一步,简单的上传功能:

  

复制代码
 public class UploadHelper
    {
        private static readonly string controller = "/api/Upload";
        /// <summary>
        /// 使用HttpClient上传附件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static async Task<string> Upload(string filePath)
        {
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            HttpContent httpContent = new StreamContent(fileStream);
            httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            string filename = filePath.Substring(filePath.LastIndexOf("\\") + 2);
            NameValueCollection nameValueCollection = new NameValueCollection();
            nameValueCollection.Add("user-agent", "User-Agent    Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");
            using (MultipartFormDataContent mulContent = new MultipartFormDataContent("----WebKitFormBoundaryrXRBKlhEeCbfHIY"))
            {
                mulContent.Add(httpContent, "file", filename);
                string ip = ConfigurationProvider.configuration.GetSection("webapi:HttpAddresss").Value;
                string url = "http://"+ip + controller;
                return await HttpHelper.PostHttpClient(url, nameValueCollection, mulContent);
            }

        }
    }
 public class HttpHelper
    {
        /// <summary>
        /// httpclient post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="RequestHeaders"></param>
        /// <param name="multipartFormDataContent"></param>
        /// <returns></returns>
        public  static async Task<string>  PostHttpClient(string url, NameValueCollection RequestHeaders,
             MultipartFormDataContent multipartFormDataContent)
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = delegate { return true; };
            using (HttpClient client = new HttpClient(handler))
            {
                client.MaxResponseContentBufferSize = 256000;
                client.DefaultRequestHeaders.Add(RequestHeaders.Keys[0],RequestHeaders[RequestHeaders.Keys[0]]);
                HttpResponseMessage httpResponseMessage = await client.PostAsync(url, multipartFormDataContent);
                httpResponseMessage.EnsureSuccessStatusCode();
                string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                return result;
            }
        }
    }
复制代码

然后自己再写一个api程序做为服务端用来接收请求,如下代码:

复制代码
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private IHostingEnvironment hostingEnvironment;
        public UploadController(IHostingEnvironment _hostingEnvironment)
        {
            hostingEnvironment = _hostingEnvironment;
        }
        [HttpPost]
        public IActionResult Upload()
        {
            try
            {
                var imgFile = Request.Form.Files[0];
                int index = imgFile.FileName.LastIndexOf('.');
                //获取后缀名
                string extension = imgFile.FileName.Substring(index, imgFile.FileName.Length - index);
                string webpath = hostingEnvironment.ContentRootPath;
                string guid = Guid.NewGuid().ToString().Replace("-", "");
                string newFileName = guid + extension;
                DateTime dateTime = DateTime.Now;
                //linux环境目录为/{1}/
                string path = string.Format(@"{0}/TemporaryFile/{1}/{2}/{3}", "/home/www", dateTime.Year.ToString(), dateTime.Month.ToString()
                    , dateTime.Day.ToString());
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                string imgSrc = path + @"/" + newFileName;
                using (FileStream fs = System.IO.File.Create(imgSrc))
                {
                    imgFile.CopyTo(fs);
                    fs.Flush();
                }
                return new JsonResult(new { message = "OK", code = 200 });
            }
            catch (Exception e)
            {
                return new JsonResult(new {message=e.Message,code=500});
            }
        }
复制代码

api程序记得修改Program.cs

 

复制代码
  public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
         //本地启动
        //public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        //    WebHost.CreateDefaultBuilder(args).UseUrls("http://*:5000")
        //        .UseStartup<Startup>();
        //linux启动
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
复制代码

当时我访问出现502就是因为这个原因

然后本地测试可以之后再将api部署到linux服务器,部署linux需要一下工具:

 XFTP:将发布好的api程序传到linux,

Ngnix:反向代理,参考菜鸟教程https://www.runoob.com/linux/nginx-install-setup.html,我的配置是这个,记得将5000加入防火墙,并且网络策略这个端口:

复制代码
user www www;
worker_processes 2; #设置值和CPU核心数一致
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志级别
pid /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
  use epoll;
  worker_connections 65535;
}
http
{
 
 #下面是server虚拟主机的配置
        server {
    listen 80;
    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

}
复制代码

具体的部署过程网上很多教程。部署好之后就可以试着用postman或浏览器输入地址访问了。

因为linux的机制当你退出linux后就无法访问,所以需要配置进程守护,我的配置如下

复制代码
[program:BlogApi]
command=dotnet BlogApi.dll
directory=/home/wwwroot/BlogAPI/
stderr_logfile=/var/log/BlogApi.error.log
stdout_logfile=/var/log/BlogApi.stdout.log
environment=ASPNETCORE_ENVIRONMENT=Production
user=root
stopsignal=INT
autostart=true
autorestart=true
startsecs=3
复制代码

更新重启守护进程,然后你就可以随时随地访问了,

 

打个广告:游戏也能赚钱?如果你热爱游戏,并且想通过游戏赢得零花钱,5173是个不错的选择  

 

posted @   灬丶  阅读(1497)  评论(8编辑  收藏  举报
编辑推荐:
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
点击右上角即可分享
微信分享提示