chào anh/chị,
Em mới làm web api em muốn upload file mà sao em truyền file và dữ liệu từ form qua apicontroller thì nó null. Anh/chị có thể chỉ giúp em với được không ạ
<form id="upload_form" @*method="post" action="api/FileAPI/UploadEbook" role="form" enctype="multipart/form-data">
<div id="modal" class="modal-body">
<div class="form-group">
<label for="text">Tiêu đề:</label>
<input type="text" class="form-control" id="Title" placeholder="Tiêu đề" name="Title">
</div>
<div class="form-group">
<label for="text">Giới thiệu:</label>
<input type="text" class="form-control" id="Describe" placeholder="Giới thiêu" name="Describe">
</div>
<div class="form-group">
<label for="text">Tác giả:</label>
<input type="text" class="form-control" id="Authỏ" placeholder="Tiêu đề" name="Author">
</div>
<div class="form-group">
<label for="text">Browser</label>
@*<input type="file" class="form-control" id="files" placeholder="" name="files">*@
<input type="file" name="Files" id="Files" />
</div>
</div>
</form>
$(document).ready(function () {
$("#upload").click(function (e) {
//e.preventDefault();
$.ajax({
type: "POST",
url: "/api/FileAPI/UploadEbook",
data: $('#upload_form').serializeJSON(),
dataType: "json",
success: function (result) {
alert("thành công");
}
});
});
[Route("api/FileAPI/UploadEbook")]
[HttpPost]
public Post UploadEbook(Post post)
{ // upload file
foreach (var file in post.Files)
{
if (file != null && file.ContentLength > 0)
{
string temp = RandomString(10, true) + "-";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/file"), temp + fileName);
file.SaveAs(path);
}
}
using (LibraryEntities db = new LibraryEntities())
{
db.Ebooks.Add(new Ebook
{
title = post.ebook.Title,
author = post.ebook.Author,
describe = post.ebook.Describe,
year = post.ebook.Year,
//filename = filename
});
public class EbookViewModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public String Describe { get; set; }
//public HttpPostedFileBase FileReferences { get; set; }
}
public class Post
{
public EbookViewModel ebook { get; set; }
//public HttpPostedFileBase file { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
Anh/chị có thể giúp em được không ạ. Em cảm ơn nhiều ạ
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?