View:
留意須要自行定義encType作multipart/form-data, 不然的話controller 不會接到file value.
@using (Html.BeginForm("CreatePost", "Email",FormMethod.Post, new { enctype= "multipart/form-data", id="formSendEmail" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<input type="file" id="attachments" name="attachments[]" multiple />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create with file" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
這裡用了賤招. 在Request.Files中取得file. 為什麼要這樣做呢? 因為若在Controller parameter 中call 入的話, 它只支援一個file. 若多於一個file 的話, 第二個file 也只會顯示第一個file的內容. 因此在這兒用了這個做work-around.
而在move file 時, 須留意UNC path 的user name, 若果會用AD / LDAP 的話, 須要準備user 的FQDN (e.g. [email protected]).
[HttpPost]
public ActionResult CreatePost()
{
IList<HttpPostedFileBase> attachments = null;
if (Request.Files.Count > 0)
{
attachments = new List<HttpPostedFileBase>();
foreach (string fileName in Request.Files)
{
attachments.Add(Request.Files[fileName]);
}
}
string attachmentPath = ConfigurationManager.AppSettings["AttachmentCachePath"]
.Replace("[[REQUEST_DATETIME]]", DateTime.Now.ToString("yyyyMMddHHmmss"))
.Replace("[[RANDOM_STRING]]", this.RandomString(attachmentCachePathRandomStringSize)
);
foreach (HttpPostedFileBase attachment in attachments)
{
// Move file to target path.
string filePath = attachmentPath + @"\" + attachment.FileName;
using (NetworkShareAccesser.Access(ConfigurationManager.AppSettings["AttachmentCacheComputerName"], ConfigurationManager.AppSettings["AttachmentCachePathUserName"], ConfigurationManager.AppSettings["AttachmentCachePathUserPassword"]))
{
if (!Directory.Exists(attachmentPath))
Directory.CreateDirectory(attachmentPath);
using (MemoryStream ms = new MemoryStream())
{
attachment.InputStream.CopyTo(ms);
System.IO.File.WriteAllBytes(filePath, ms.ToArray());
}
}
}
Leave a Reply