i am trying to upload files with the jqueryform plugin. I have to file upload controls but the second one cant upload?
<div>
<h2>
Upload test</h2>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function (event) {
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: ' Uploading Image' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
//$.growlUI(null, result.message);
if (result.message != 'Success') {
alert(result.message);
}
else {
}
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
}
});
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("Upload", "Home")%>" method="post"
enctype="multipart/form-data">
<input type="file" name="file" />
<input type="file" name="file2" />
<input id="ajaxUploadButton" type="submit" value="upload file" />
</form>
</div>
public ActionResult Index()
{
return View();
}
public FileUploadJsonResult Upload(HttpPostedFileBase file)
{
if (file == null)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
if (file.ContentLength > 0)
{
//save file or something
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
public class FileUploadJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
this.ContentType = "text/html";
context.HttpContext.Response.Write("<textarea>");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea>");
}
}
You have two file inputs on your form named respectively file and file1. You controller action that handles the upload has only a single HttpPostedFileBase argument named file. So you could add a second one:
public FileUploadJsonResult Upload(
HttpPostedFileBase file,
HttpPostedFileBase file1
)
{
if (file == null || file1 == null)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
if (file.ContentLength > 0)
{
//save file or something
}
if (file1.ContentLength > 0)
{
//save the second file or something
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
Or if you wanted to handle multiple files you could give them the same name on your form:
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
...
and your controller action could then take a list of files:
public FileUploadJsonResult Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
foreach (var file in files)
{
if (file.ContentLength > 0)
{
//save file or something
}
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
You may checkout the following blog post about uploading files in ASP.NET MVC.
Related
I have the following code which works with input type file, I did some changes by replacing the input type file with filepond plugin. I am unable to post it to controller. Is it possible to add a new object to FormData?
I have my model as follows
public class ReportableEventModel
{
public string IMONumber { get; set; }
public string VesselName { get; set; }
public List<HttpPostedFileBase> Documents { get; set; }
}
This is my view
using (Html.BeginForm("ReportablEventUpdate", "Reportable", FormMethod.Post, new { #id = "EventEdit", ReportableEventId = Model.ReportableEvent.ReportableEventId, enctype = "multipart/form-data" }))
{
<input type="number" class="form-control" id="IMONumber" name="IMONumber" required placeholder="Enter IMO No" value="#Model.IMONumber" onkeydown="return event.keyCode !== 69" maxlength="7" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
<input type="text" class="form-control" id="VesselName" name="VesselName" required placeholder="Enter Vessel Name" value="#Model.VesselName">
<input type="file" class="filepond adminPond" name="Documents" multiple />
<button class="btn btn-primary" id="btn-submit1" type="submit" onclick="return validateSubmit();">Save</button>
}
This is how I am changing the file to filepond
<script type="text/javascript">
var adminPond;
var adminFileNames = [];
FilePond.registerPlugin(
FilePondPluginFileEncode,
FilePondPluginImageExifOrientation
);
adminPond = FilePond.create(
document.querySelector(
'input.adminPond'));
adminPond.on('addfile', function (error, file) {
if (adminFileNames.includes(file.filename)) {
var fileError = "A file with name " + file.filename + " was already uploaded";
createToast("Error", fileError, TOAST_STATUS.DANGER);
handleFileError(file, adminPond);
}
adminFileNames.push(file.filename);
});
adminPond.on('removefile', function (err, f) {
adminFileNames = [];
var fileCnt = adminPond.getFiles().length;
for (var fCnt = 0; fCnt < fileCnt; fCnt++) {
var file = adminPond.getFile(fCnt);
adminFileNames.push(file.filename);
}
});
On submit I am trying as follows to append the uploaded files but not working,
function validateSubmit() {
var data = new FormData($("#EventEdit")[0]);
let files = adminPond.getFiles().length;
for (let i = 0; i < files; i++) {
data.append(`Document[${i}]`, adminPond.getFile(i).file);
}
showSpinner();
return true;
}
So can some one let me know how can I pass an item to the form using FormData, here is the jquery fiddle of file pond I am using
https://jsfiddle.net/DorababuMeka/ydj2aruL/
So I'm trying to build an virtual file storage, im stuck at the part where I have to upload files and after that display them in a File-s view so that the user can download, delete or see them. The form input together with the file upload is in a modal box. To process the modal form I have used #Html.BeginForm and to process the file upload I have used ajax. What I have achieved until now is that I can upload the files to the server folder, but I dont konw how I can save the file name and the file path to the database of file-s table. And I also need help on how to display these files in a specific view. Thank you in advance.
Html
<div class="modal-body">
#using (Html.BeginForm("SaveRecord", "NgarkoDokument", FormMethod.Post, new { enctype = "mulptiple/form-data" }))
{
<div class="form-group">
<label for="exampleFormControlSelect1">Lloji i dokumentit</label><br />
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
<input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
<input type="file" onchange="javascript: updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles"/>
<div id="fileList"></div>
</div>
<br /><br />
<div class="form-group">
<label for="formGroupExampleInput">Fusha indeksimi</label> <br />
#*<input title="Indeksimi dokumentit" id="indeksimi" class="form-control col-md-3" type="text" name="indeksimi" placeholder="indeksimi" required />*#
#Html.TextBoxFor(a => a.Fusha_Indeksimit.Emri_Indeksimit, new { #class = "form-control", #placeholder = "indeksimi" })
#* <button title="Shto indeksim" id="modalPlus" type="submit" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i></button>*#
</div>
<label for="formGroupExampleInput">Vendndodhja fizike e dokumentit</label><br>
<div id="zyraModal" class="form-group col-md-4">
#*<input title="Zyra fizike" id="zyra" class="form-control" type="text" name="zyra" placeholder="Zyra" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Zyra, new { #class = "form-control", #placeholder
= "Zyra" })
</div>
<div class="form-group col-md-4">
#* <input title="Kutia fizike" id="kutia" class="form-control" type="number" name="kutia" placeholder="Nr i kutisë" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Nr_Kutise, new { #class = "form-control", #placeholder = "Nr i kutisë" })
</div>
<div class="form-group col-md-4">
#* <input title="Rafti fizik" id="rafti" class="form-control" type="text" name="rafti" placeholder="Rafti" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Rafti, new { #class = "form-control", #placeholder = "Rafti" })
</div>
<br /><br />
<div class="row" id="ruaj">
<button title="Ruaj dokumentin" type="submit" class="btn btn-success">Ruaj</button>
</div>
}
</div>
Ajax script
<script type="text/javascript">
$(document).ready(function () {
$("#file").change(function () {
console.log("Image selected!");
var formData = new FormData();
var totalFiles = document.getElementById("file").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file").files[i];
formData.append("file", file);
}
$.ajax({
type: "POST",
url: '/UploadFile/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
}
});
});
});
</script>
Controller
public ActionResult Dokument()
{
return View();
}
[HttpPost]
public void Upload()
{
Dokumenti dok = new Dokumenti();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/File/"), fileName);
file.SaveAs(path);
}
}
public ActionResult SaveRecord(NgarkoDokument model)
{
try
{
Vendndodhja_Fizike vendndodhja = new Vendndodhja_Fizike();
vendndodhja.Zyra = model.Vendndodhja_fizike.Zyra;
vendndodhja.Rafti = model.Vendndodhja_fizike.Rafti;
vendndodhja.Nr_Kutise = model.Vendndodhja_fizike.Nr_Kutise;
db.Vendndodhja_Fizike.Add(vendndodhja);
Fusha_Indeksimit indeksimi = new Fusha_Indeksimit();
indeksimi.Emri_Indeksimit = model.Fusha_Indeksimit.Emri_Indeksimit;
db.Fusha_Indeksimit.Add(indeksimi);
Dokumenti dok = new Dokumenti();
dok.Emer = model.Dokumenti.Emer;
db.Dokumenti.Add(dok);
db.SaveChanges();
//int lastUserId = dok.UserID;
}
catch(Exception ex)
{
throw ex;
}
return RedirectToAction("Dokument");
}
}
First of all, you may need to specify this because you send FormData to your controller. For example:
public async Task CreateAsync([FromForm] CreateBookDto input)
{
...
}
I care about a lot of things while uploading the file so my js file is a bit long but you can get what works for you:
$(function () {
var fileInput = document.getElementById('Book_CoverImageFile');
var file;
fileInput.addEventListener('change', function () {
var showModal = true;
file = fileInput.files[0];
document.getElementById("choose-cover-image").innerHTML = file.name;
var permittedExtensions = ["jpg", "jpeg", "png"]
var fileExtension = $(this).val().split('.').pop();
if (permittedExtensions.indexOf(fileExtension) === -1) {
showModal = false;
alert('This extension is not allowed')
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
else if(file.size > 5*1024*1024) {
showModal = false;
alert('The file is too large');
}
var img = new Image();
img.onload = function() {
var sizes = {
width:this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
if (sizes.width > 1920 && sizes.height > 1080){
alert('Height and Width must not exceed 1920*1080.')
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
var aspectRatio = sizes.width / sizes.height;
aspectRatio = Number (aspectRatio.toFixed(1));
if (aspectRatio !== 1.8){
alert("The picture you uploaded is not in 16:9 aspect ratio!")
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
}
if(showModal === true) {
readURL(this);
$('#myModal').modal('show');
}
var objectURL = URL.createObjectURL(file);
img.src = objectURL;
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('form#CreateBookForm').submit(function (e) {
e.preventDefault();
var title = $('#Book_Title').val().trim();
var formData = new FormData();
formData.append("Title", title);
formData.append("CoverImageFile", file);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
if(percentComplete !== 100){
$( '#Book_CoverImageFile' ).prop( "disabled", true );
$( '#Book_Title' ).prop( "disabled", true );
$( '#btnSubmit' ).prop( "disabled", true );
}
}
}, false);
return xhr;
},
url: app.appPath + `api/app/Book`,
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data){
alert("The Book has been successfully submitted. It will be published after a review from the site admin.");
window.location.href = "/books";
},
error: function (data) {
alert(data.responseJSON.error.message);
}
});
});
This does many things, for example; file permitted extension control, control of file size, checking whether the file is more than 1920 * 1080 pixels, whether the file has 16:9 aspect ratio, disabling form elements while sending the file, etc...
And if you really care about security, you should;
To only accept permitted extensions:
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNul
{
return ValidationResult.Success;
}
var file = value as IFormFile;
var extension = Path.GetExtension(file.FileName);
if (file.Length > 0 && file != null)
{
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"This extension is not allowed!";
}
}
To limit the uploaded file size:
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNull
{
return ValidationResult.Success;
}
var file = value as IFormFile;
if (file.Length > 0)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is { _maxFileSize} bytes.";
}
}
And you must add them to Dto:
public class CreateBookDto
{
[Required]
[StringLength(64)]
public string Title { get; set; }
[CanBeNull]
[DataType(DataType.Upload)]
[MaxFileSize(5*1024*1024)] // 5mb
[AllowedExtensions(new string[] { ".jpg", ".png", ".jpeg" })]
public IFormFile CoverImageFile { get; set; }
}
Finally, your HTML file should look like this:
<form method="post" id="CreateBookForm" asp-page="/Book/Create" enctype="multipart/form-data">
<div class="form-group">
<div class="custom-file">
<input asp-for="Book.CoverImageFile" type="file" name="file" class="custom-file-input" id="Book_CoverImageFile"
required="required">
<label id="choose-cover-image" class="custom-file-label" for="customFile">Choose a cover image...</label>
<small class="form-text text-muted">#L["CreateBookCoverInfo"].Value</small>
</div>
</div>
...
<button id="btnSubmit" type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<img class="img-fluid" id="img-upload" alt=""/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-block" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I need to pass Hidden ID value var genericID = $("#hdnGenericID").val(); to FromData.But i can't able to pass Id Value.
how to pass the hdnGenericID ID value to controller.
#Html.HiddenFor(model => item.GenericID, new { id = "hdnGenericID" })
cs.Html
<div class="uploading-container">
<div class="uploading-container-left">
<span class="btn btn-rounded btn-file">
<span>Choose file</span>
<input type="file" name="file" id="file">
</span>
</div><!--.uploading-container-left-->
<div class="uploading-container-right">
<div class="uploading-container-right-in">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label semibold">Perview_Image</label>
<img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
<a id="remove" onclick="javascript:ClearFileUploadControl();" style="display: none; cursor: pointer;">Remove</a>
</fieldset>
</div>
<input type="submit" id="btnImageUpload" name="ImageUpload" value="Upload image" class="btn btn-rounded btn-inline btn-success" />
</div>
</div>
</div>
Image Upload:
$(function () {
$('#btnImageUpload').click(function () {
var data = new FormData();
var genericID = $("#hdnGenericID").val();
var files = $("#file").get(0).files;
if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var extension = $("#file").val().split('.').pop().toUpperCase();
if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
return false;
}
$.ajax({
url: '../Generic/SaveProfileImage',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (data) {
if (data == true) { // if true (1)
setTimeout(function () {// wait for 1 secs(2)
location.reload(); // then reload the page.(3)
}, 1000);
}
},
error: function (er) { }
});
return false;
});
});
Controller:
[HttpPost]
public ActionResult SaveProfileImage()
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = docId.ToString() + ".png";
var path = Path.Combine(Server.MapPath("~/UploadGenericImage/"), fileName);
filebase.SaveAs(path);
//return Json("File Saved Successfully.");
return Json(new { data = true});
}
else { return Json("No File Saved."); }
}
catch (Exception ex) { return Json("Error While Saving."); }
}
Change the script like this
$(function () {
$('#btnImageUpload').click(function () {
var data = new FormData();
var genericID = $("#hdnGenericID").val();
data.append("GenericID", genericID);
var files = $("#file").get(0).files;
if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var extension = $("#file").val().split('.').pop().toUpperCase();
if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
return false;
}
$.ajax({
url: '../Generic/SaveProfileImage',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (data) {
if (data == true) { // if true (1)
setTimeout(function () {// wait for 1 secs(2)
location.reload(); // then reload the page.(3)
}, 1000);
}
},
error: function (er) { }
});
return false;
});
});
and change the controller like this
[HttpPost]
public ActionResult SaveProfileImage(string GenericID)
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = docId.ToString() + ".png";
var path = Path.Combine(Server.MapPath("~/UploadGenericImage/"), fileName);
filebase.SaveAs(path);
//return Json("File Saved Successfully.");
return Json(new { data = true});
}
else { return Json("No File Saved."); }
}
catch (Exception ex) { return Json("Error While Saving."); }
}
then in controller you will be able to access the value of GenericID.
did you try using FormCollection parameter to controller action method i.e.
[HttpPost]
public ActionResult SaveProfileImage(FormCollection form,string GenericID)
{....
}
this form will have your hiddenfield value and can access hiddenfield like below
var hiddenFieldValue = form["hdnGenericID"] ..
This is my View
Test Upload File
<form action="#Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
This is my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = file.FileName;
var path = Path.Combine(Server.MapPath(#"\Upload"), fileName);
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
}
return View();
}
The problem is the HttpPostedFileBase files is always null. I cant find the problem.
Here is an example how to use form onsubmit method
Your HTML part
<form id="formTest" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
script
<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
e.preventDefault();
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('files');
if (fileInput != "" && fileInput.files.length > 0) {
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
var url = '#Url.Action("Index","Home")';
xhr.open('POST', url);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
}
}
return false;
}
}
</script>
C#
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return View();
}
}
You can also handle files with Request.Files like this:
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
}
And for your second question, please try to use it between Html.BeginForm instead of form like this:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<label>Filename:</label>
<input type="file" name="file1"/>
<input type="submit" name="submit" value="Upload" />
}
I need to save canvas image by using ajax or javascript...!!
tks!
my view
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData"/>
<input type="button" id="btnSave" value="Save Drawing"/>
}
[HttpPost]
public ActionResult SaveImage(CampaignViewModel model, string imageData)
{
//code.....
return RedirectToAction("Index", "Home");
}
We in ImindQ Online export the canvas as PNG with the following adapted code for your scenario:
In view:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Image</title>
</head>
<body>
<div>
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData" />
<input type="button" id="btnSave" value="Save Drawing" />
}
<script>
(function () {
document.getElementById('btnSave').addEventListener('click', function () {
var r = new XMLHttpRequest();
r.open("POST", "SaveImage", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
};
var p = document.getElementById('myCanvas').toDataURL('image/png').replace('data:image/png;base64,', '');
r.send(p);
});
})();
</script>
</div>
</body>
</html>
in Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
//public class CampaignViewModel
//{
// public string ImageData { get; set; }
//}
public class CampaignController : Controller
{
// GET: Campaign
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveImage()
{
int len = (int)Request.InputStream.Length;
byte[] buffer = new byte[len];
int c = Request.InputStream.Read(buffer, 0, len);
string png64 = Encoding.UTF8.GetString(buffer, 0, len);
byte[] png = Convert.FromBase64String(png64);
System.IO.File.WriteAllBytes("d:\\a.png", png);
//string pngz = Encoding.UTF8.GetString(png, 0, png.Length);
//code.....
return RedirectToAction("Index", "Home");
}
//
}
}
in view :
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData"/>
<input type="button" onclick="saveimage(event)" id="btnSave" value="Save Drawing" />
<img style="display: none" src="images/ajax-loader/ajax-loader.gif" id="progressbar"/>
}
#*call action*#
<script>
function saveimage(event) {
#*prevent call back to server*#
event.preventDefault();
#*show progress bar *#
var progress = document.getElementById("progressbar");
$(progress).css('display', 'block');
#*get form data *#
var data = $("#drawingForm").serialize();
#*save image information to imageData tag *#
var image = document.getElementById("myCanvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$("#imageData").val(image);
#*make ajax call *#
$.ajax({
url: "/Campaign/SaveImage",
data: data,
type: "Post",
dataType: "Json",
success: function (data) {
//do something
},
error: function (xhr, status, error) {
//do something
},
complete: function (data) {
$(progress).css('display', 'none');
}
});
}</script>
and in controller :
[HttpPost]
public ActionResult SaveImage(CampaignViewModel model, string imageData)
{
//path of folder taht you want to save the canvas
var path = Server.MapPath("~/images/canvaseimg");
//produce new file name
var fileName = GetPictureName(path);
//get full file path
var fileNameWitPath = Path.Combine(path, fileName);
//save canvas
using (var fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{
var data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
fs.Close();
}
//do somthing with model
return RedirectToAction("Index", "Home");
}