Popular blog tags

  

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

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