linux部署.net core api而且實現上傳圖片

爲了體驗.net在linux上運行,因此使用HttpClient東借西抄作了一個簡單的api上傳功能。html

第一步,簡單的上傳功能:linux

  

 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程序作爲服務端用來接收請求,以下代碼:nginx

    [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.csweb

 

  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

而後本地測試能夠以後再將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或瀏覽器輸入地址訪問了。async

由於linux的機制當你退出linux後就沒法訪問,因此須要配置進程守護,個人配置以下ide

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

相關文章
相關標籤/搜索