@{
ViewBag.Title = "多檔案上傳測試";
}
<h2>多檔案上傳測試</h2>
<form action="/Demo/Index" method="post" enctype="multipart/form-data">
<input type="file" /><br />
<input type="file" /><br />
<input type="file" /><br />
<input type="submit" value="上傳" />
</form>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZhaoWoAPI.Models;
namespace ZhaoWoAPI.Controllers
{
public class DemoController : Controller
{
[HttpPost]
public ActionResult Index(string content)
{
try
{
FileLogModel.Log("========================開始上傳圖檔=====================:content=" + content);
HttpFileCollectionBase files = Request.Files;
FileLogModel.Log("==================上傳圖檔數量為:" + files.Count+"===========================");
if(files.Count<=0)
{
FileLogModel.Log("=================無上傳圖檔===================================" );
return Content("0");
}
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase hpf = files[i];
if (hpf.ContentLength <= 0)
{
continue;
}
var extension = Path.GetExtension(hpf.FileName);
FileLogModel.Log("=====================檔案字尾名:"+extension+"==========================");
string datename = DateTime.Now.ToString("yyyy-MM-dd");
string path = Server.MapPath("/Resource/SendInfo/" + datename + "/");
FileLogModel.Log("=====================上傳路徑:" + path + "==========================");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string newfilename = path + ZhaoWoCommon.GUIDTools.GetGUID() + extension;
FileLogModel.Log("=====================完整路徑:" + newfilename + "==========================");
hpf.SaveAs(newfilename);
}
FileLogModel.Log("=====================上傳成功==========================" );
return Content("ok");
}
catch (Exception ex)
{
FileLogModel.Log("上傳失敗"+ex.Message );
return Content("error");
}
}
public ActionResult Test()
{
return View();
}
}
}