Files
17168ERP/web/App_Code/api/fileSystemController.cs
2025-08-29 01:27:25 +08:00

93 lines
2.6 KiB
C#

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/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody] string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
[HttpPost]
[Route("api/fileSys/upload")]
public async Task<IHttpActionResult> 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();
}
}
}