using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UpLoadController : ControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public UpLoadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        public string Post([FromForm] IFormCollection formCollection)
        {
            string result = "";
            string webRootPath = _hostingEnvironment.ContentRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            FormFileCollection filelist = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in filelist)
            {
                String Tpath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                string name = file.FileName;
                string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string FilePath = webRootPath + Tpath;

                string type = Path.GetExtension(name);
                DirectoryInfo di = new DirectoryInfo(FilePath);

                if (!di.Exists)
                {
                    di.Create();
                }

                using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result = "1";
            }
            return result;
        }
    }
}

Unity中调用

    private IEnumerator UpLoadImg(string filePath)
    {   
        byte[] bs = File.ReadAllBytes(filePath); 
        Log.Debug("bs.Length:" + bs.Length.ToString());  
        WWWForm test = new WWWForm();
        test.AddBinaryData("imgbase.jpg", bs, "imgbase.jpg");
        WWW www = new WWW("http://192.168.2.185/api/upload", test);
        yield return www;
        Log.Debug(www.text);
    }

标签: asp.net core

添加新评论