Written by
in
การ upload file มีหลายรูปแบบ ไม่ว่าจะเป็นการ upload file แบบ copy ไว้บน server หรือจะเป็นการบันทึกลงในฐานข้อมูลเลยโดยตรง วันนี้จะขอนำเสนอในส่วนของการ upload file และบันทึกลงฐานข้อมูล โดยใช้ ASP.NET MVC ดังนี้
กำหนดไฟล์ที่ต้องการ upload ให้มีรูปแบบดังนี้
{
[Required]
public HttpPostedFileBase File { get; set; }
}
ในส่วนของ View
<a type=”submit” href=”#” onclick=”uploadConfirm();” class=”btn btn-info”><span class=”glyphicon glyphicon-save”></span> Upload</a>
</form>
ในส่วนของ java script (สำหรับเรียก Controller)
$.ajax({
type: ‘POST’,
contentType: ‘application/json; charset=utf-8’,
url: ‘@Url.Action(“CheckDataBeforeUpload”, “NoteUpload”)’,
data: “{ ‘periodID’:’” + $(‘#selectedlistPeriods’).val() +
“‘ ,’financeID’:’” + $(‘#selectedlistFinance’).val() +
“‘ }”,
success: function (resultSave) {
},
error: function (data) {
alert(data);
});
ในส่วนของ Controller
string fileName = Path.GetFileName(model.File.FileName); //แสดงชื่อไฟล์
string strFileName = Path.GetFileNameWithoutExtension(fileName); //แสดงชื่อไฟล์
string contentType = model.File.ContentType; //แสดงนามสกุลไฟล์
string FileExtension = fileName.Substring(fileName.LastIndexOf(‘.’) + 1).ToLower();
using (Stream fs = model.File.InputStream) //
using (BinaryReader br = new BinaryReader(fs))
byte[] bytes = br.ReadBytes((Int32)fs.Length);
//TO DO: Code ในส่วนที่ต้องการ insert ข้อมูลลง Database
return RedirectToAction(“Index”);
จากตัวอย่างข้างต้น จะเป็นการ upload file ลงฐานข้อมูลโดยตรงในส่วนของรูปแบบการพัฒนาแบบ MVC ผู้เขียนหวังว่าอาจจะเป็นอีกทางเลือกหนึ่งของผู้พัฒนา ในการนำไปพัฒนาโปรแกรมต่อไปนะคะ ^_^
แหล่งอ้างอิง
https://stackoverflow.com/questions/15106190/uploading-files-into-database-with-asp-net-mvc
https://stackoverflow.com/questions/21677038/mvc-upload-file-with-model-second-parameter-posted-file-is-null/21677156
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Website
Save my name, email, and website in this browser for the next time I comment.
Δ
Leave a Reply