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是個不錯的選擇  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM