How to upload Single/Multiple images in ASP.NET Core/MVC

preview_player
Показать описание
Sample Code.
Inside Controller function ,
try
{
//accessing header properties values
var filetype = HttpContext.Request.Headers["type"].FirstOrDefault();
var description = HttpContext.Request.Headers["session"].FirstOrDefault();

//accessing uploaded files
var files = HttpContext.Request.Form.Files;
foreach(var item in files)
{
var currentfile = Path.Combine("wwwroot", "Upload\\" + item.FileName);
using (var stream = new FileStream(currentfile, FileMode.Create))
{
await item.CopyToAsync(stream);
}
}

return Json(new { status = true, message = "message from server" });
}
catch (Exception ex)
{
return Json(new { status = false });
}
finally
{
//file.InputStream.Close();
}

In Html/Razor Page,
----------------------------------------------------------------------------------------

Dropzone function: replace greaterthan symbol
---------------------------------------------------------

$(document).ready(function () {

var $myDropZone = new Dropzone('div#ImageDrop', {
url: "/Home/UploadMultiStream",//when file uploading which server function should trigger in controller
addRemoveLinks: true,
uploadMultiple: false,
//parallelUploads: 5,
maxFilesize: 3.0,
timeout: 864000,
acceptedFiles: ".jpeg,.jpg,.png",
maxFiles: 1,//also increase this value
dictDefaultMessage: "Please drop/select the image in jpeg/png format only and Upload",
previewsContainer: '#preview',
headers: {
'session': 'test',
'type': '1'
},
init: function () {
}
});

$(".dz-success-mark svg").css("background", "green");
$(".dz-error-mark").css("display", "none");
$('#waiting').css('display', 'none');
$('#previewhead').css('display', 'block');
$('#servermessage').css('display', 'block');

});
$(".dz-success-mark svg").css("background", "green");
$(".dz-error-mark").css("display", "none");
alert("removed");
});
$(".dz-error-mark svg").css("background", "red");
$(".dz-success-mark").css("display", "none");


alert("Remove uploaded file and re-upload");
}

alert("Only jpg or png files only accepted");
}
if (message == "Server responded with 0 code.") {
alert("Server failed to upload image. Try later!");
}
})
$('#waiting').css('display', 'block');
});

});
Рекомендации по теме