using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; [ezAuthorize] public class fileSystemController : ApiController { // GET api/ public IEnumerable Get() { return new string[] { "value1", "value2" }; } // GET api//5 public string Get(int id) { return "value"; } // POST api/ public void Post([FromBody] string value) { } // PUT api//5 public void Put(int id, [FromBody] string value) { } // DELETE api//5 public void Delete(int id) { } [HttpPost] [Route("api/fileSys/upload")] public async Task uploadFile() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } try { var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); //var path = HttpContext.Current.Server.MapPath("~/upload"); //var path = System.Web.HttpContext.Current.Server.MapPath(Model.project.Dir); string dir = "upload/project"; //多執行緒之下抓不到HttpContext.Current var path = HttpContext.Current != null? HttpContext.Current.Server.MapPath(Model.project.Dir) : System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string pic1 = ""; int ii = 0; foreach (var file in provider.Contents) { var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); //從header去取得filename的名字 string[] n = Path.GetFileName(fileName).Split('.'); fileName= DateTime.Now.ToString("yyyyMMddHHmmss") + ii.ToString() + "." + n[n.Length - 1]; pic1 += (!string.IsNullOrEmpty(pic1) ? "," : "") + fileName; var fullPath = File.Create($"{path}/{fileName}"); var buffer = await file.ReadAsByteArrayAsync(); await fullPath.WriteAsync(buffer, 0, buffer.Length); ii++; } return Ok(pic1); } catch(Exception e) { return NotFound(); } } }