通过文件上传添加新数据
本文关键字:数据 新数据 添加 文件 | 更新日期: 2023-09-27 18:34:11
我有这个表单,它有两个字段,一个名称和一个图像字段。下面是表单的代码
@using (Html.BeginForm("AddNewRecipe", "Kitchen", FormMethod.Post, new { enctype = "multipart/form-data", id = "addNewRecipe", data_partitionId = Model.Id }))
{
<input type="text" placeholder="Recipe Name" name="newRecipeName" id="newRecipeName" value="" />
<input type="file" accept="image/*" name="newRecipeImage" id="newRecipeImage" value="" />
<button type="submit" class="button small" id="submitnewRecipe">Add</button>
}
当表单提交时,我正在我的JavaScript中执行此操作,
$('form#addNewRecipe').submit(function (event) {
event.preventDefault();
var data = new FormData();
var files = $('#newRecipeImage').get(0).files;
if (files.length > 0) {
data.append("UploadedImage", files[0]);
}
console.log(data); // no data is appended
});
我在这里尝试做的是将图像文件和名称发送到服务器,以便可以上传它们。关于如何做到这一点的任何见解?
我正在寻找一个很好的解决方案 asp.net mvc c#。
也许我的技术不太好。我愿意接受批评。:)
我在我的项目中使用它(工作代码)
jquery
var formData = new FormData();
var files = $('#newRecipeImage').get(0).files;
if (files.length > 0) {
formData.append("img", files[0]);//files[0].name contains the file name
}
$.ajax({
cache: false,
type: 'POST',
data: formData,
processData: false,
contentType: false,
url: '/Sport/GetImagePreview',
success: function(data) {
//$("#yourImage").attr("src", "data:image/png;base64," + data.base64imgage);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
然后在控制器中
[HttpPost]
public JsonResult GetImagePreview()
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var img = System.Web.HttpContext.Current.Request.Files["img"];//Request.FILES['img'].name contains the file name
var ms = new MemoryStream();
var logo = Image.FromStream(img.InputStream);
logo = FixedSize(logo, 150, 150);
logo.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Json(new {base64imgage = Convert.ToBase64String(ms.ToArray())});
}
return Json("ko");
}
catch (Exception)
{
return Json("ko");
}
}