Free text editor with image gallery - asp.net-mvc

Hi i want a free text editor with image or file gallery and i want to insert image or file in the middle of the text.
Please give me your suggestions.

ckeditor(text)+ckfinder(image)
Or
you can use Summernote with server side image upload setup
$('#Editor').summernote({
lang: 'fa-IR',
callbacks: {
onImageUpload: function (files) {
var $editor = $(this);
var data = new FormData();
data.append('imageFile', files[0]);
$.ajax({
url: '/Server/UploadImage',
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function (url) {
$editor.summernote('insertImage', url);
}
});
}
}
});
and MVC5 server side sample action code:
public string UploadImage()
{
HttpPostedFileBase file = null;
string RenameFile = "";
for (int i = 0; i < Request.Files.Count; i++)
{
file = Request.Files[i];
string fileExt = System.IO.Path.GetExtension(file.FileName);
Guid randomFileName = Guid.NewGuid();
RenameFile = randomFileName + fileExt;
var path = Path.Combine(Server.MapPath("~/Content/Uploads/"), RenameFile);
file.SaveAs(path);
}
return #"/Content/Uploads/" + RenameFile;
}

Related

Summernote image upload with .NET Core

Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.
I initialise Summernote using the following -
$('#MessageBody').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
Here is the uploadImage function -
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: '/EmailTemplate/UploadImage',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#MessageBody').summernote("insertNode", image[0]);
alert(url);
var imgNode = document.createElement('img');
imgNode.src = url;
$('#MessageBody').summernote('insertNode', imgNode);
},
error: function(data) {
console.log(data);
}
});
And finally, here is the controller -
[HttpPost]
public async Task<IActionResult> UploadImage(IFormFile file)
{
string message;
var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
string imgext = Path.GetExtension(file.FileName);
if (imgext == ".jpg" || imgext == ".png")
{
using (var uploadimg = new FileStream(saveimg, FileMode.Create))
{
await file.CopyToAsync(uploadimg);
message = "The selected file" + file.FileName + " is saved";
}
}
else
{
message = "only JPG and PNG extensions are supported";
}
// return "filename : " + saveimg + " message :" + message;
return Content(Url.Content(saveimg));
}
The parameter is called file while the field name is image. To fix this use the same name, either file or image.
The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.
Field binding is explained in the Sources section of the Model Binding document.

Adobe embedded PDF save to Server giving corrupt file

I am using Adobe Document Services PDF Embed API to display PDF files in my website and Iam allowing users to add sticky notes in the pdf and then save it
My problem is that i need to save the file back to the Server. But I cant find the PDF Buffer. I need to send the pdf buffer or the updated pdf to my Asp.net Conbtroller
adobeDCView.previewFile({
/* Pass information on how to access the file */
content: {
/* Location of file where it is hosted */
location: {
url: myurl,
},
},
/* Pass meta data of file */
metaData: {
/* file name */
fileName: "-VER - 0.pdf"
}
}, viewerConfig);
/* Define Save API Handler */
var saveApiHandler = function (metaData, content, options) {
console.log(metaData, content, options);
return new Promise(function (resolve, reject) {
/* Dummy implementation of Save API, replace with your business logic */
/
var formData = new FormData();
formData.append('metaData', metaData);
formData.append('content', content); // is this the pdf buffer ???
formData.append('options', options);
setTimeout(function () {
//Want to do ajax call to controller here
var response = {
code: AdobeDC.View.Enum.ApiResponseCode.SUCCESS,
data: {
metaData: Object.assign(metaData, { updatedAt: new Date().getTime() })
},
};
resolve(response);
}, 2000);
});
};
And in my controller I have
[HttpPost ]
public ActionResult GetData(object Metadata, Object content,object option)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream()) {
bf.Serialize(ms, content);
System.IO. File.WriteAllBytes(#"C:\1.pdf", ms.ToArray());
}
return View();
}
As #joelgeraci suggested Need to convert the content to base64 and add it to form data and send to Controller action( credits to the codepen provided by #joelgeraci
var base64PDF = arrayBufferToBase64(content);
var formData = new FormData();
formData.append('content', base64PDF);
Function to convert arraybuffer
function arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
And in the controller
[HttpPost]
public ActionResult GetData(object Metadata, Object content, object option, IEnumerable<HttpPostedFileBase> productImg, String DocumentID, string filename)
{
byte[] sPDFDecoded = Convert.FromBase64String(((string[])content)[0]);
string filepath = "C:\1.pdf";
System.IO.File.WriteAllBytes(filepath, sPDFDecoded);
return View();
}

How to upload a Image in Asp.net MVC using Ajax request

How to upload a Image in Asp.net MVC using Ajax request I have single controller and its view file have to use Ajax request.
Index Controller
public ActionResult Index()
{
return View();
}
and its view
Textbox with id="imageUploadForm"
<input type="file" id="imageUploadForm" name="image" multiple="multiple" />
Ajax function
$(document).ready(function() {
$("#imageUploadForm").change(function() {
var formData = new FormData();
var totalFiles = document.getElementById("imageUploadForm").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("imageUploadForm").files[i];
formData.append("imageUploadForm", file);
}
$.ajax({
type: "POST",
url: '/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false
//success: function(response) {
// alert('succes!!');
//},
//error: function(error) {
// alert("errror");
//}
}).done(function() {
alert('success');
}.fail(function( xhr, status, errorThrown ) {
alert('fail');
};
});
});
Controller Function
[HttpPost]
public void Upload()
{
if(Request.Files.Count != 0){
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/"), fileName);
file.SaveAs(path);
}
}
}

Excel file not saved in user's PC

I have tried to download an excel file from the server to user's PC. I have the following codes from the internet. I have modified the codes a bit....
But when I run the code, nothing happens. The save dialog box is not popping up. What I really want to happen is that the excel file from the server will be saved in user's PC by popping up a save dialog box.
Please help!!!
public void DownloadFile(string url)
{
string path = Server.MapPath("~/Images/0ca66926-6977-43d3-9c97-f84a43f6ce5d.xls");
var file = new FileInfo(path);
string Outgoingfile = "FileName.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
}
$.ajax({
url: '#Url.Action("DownloadFile", "Home")',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({ url: urlLink}),
success: function(res) {
},
error: (function() {
alert("Error to retrieve selected report");
})
});
Since you are looking for a working download file code, I am sharing what we use.
We have two call process to download code. First call get the file prepared and saved on server. Second call shown below read file content and return a file object.
Controller.cs:
[HttpGet]
public ActionResult DownloadStream(string fileName, int searchId)
{
var tempStore = _searchService.GetTempStore(searchId);
var bytes = tempStore.DataAsBlob;
if (bytes != null)
{
var stream = new MemoryStream(bytes);
_searchService.DeleteTempStore(searchId);
return File(stream, "application/vnd.ms-excel", fileName);
}
_logger.Log("Export/DownloadStream request failed", LogCategory.Error);
return Json("Failed");
}
View.cshtml
Following line calls DownloadStream method on server, server send a file object that gets save on user machine.
window.location = '/Export/DownloadStream?fileName=' +
result+"&searchId="+searchId;
function ExportData(exportType, exportFormat) {
var searchId = document.getElementById('hfSelectedDriverId').value;
var model = { searchId: searchId, exportType: exportType, exportFormat: exportFormat };
$.ajax({
url: '#Url.Action("ExportDriverFile", "Export")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function (result) {
result = result.toString().replace(/"/gi, "");
if (result == "" || result == "failed")
{
alert("File download failed. Please try again!");
}
else
{
window.location = '/Export/DownloadStream?fileName=' + result+"&searchId="+searchId;
}
})
.error(function (xhr, status) {
//alert(status);
});
}

Want to Save Posted Json data to database

I am posting JSON data through AJAX POST as ::
var length = $('.organizer-media').length;
var contents = $('.organizer-media');
var Title;
type == "New" ? Title = $('#newName').val() : Title = $('#Playlist option:selected').text();
var playlistid = $('#Playlist').val()
type == "New" ? playlistid = 0 : playlistid = $('#Playlist').val()
var data = [];
for (var i = 0; i < length; i++) {
data[i] = { ID: parseInt(contents[i].id), MetaID: parseInt(contents[i].title) }
}
var totaldata={ data: data, playlistid: parseInt(playlistid),Title:Title };
$.ajax({
type: 'POST',
data: JSON.Stringify(totaldata),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
the JSON data is sent in following format::
{"data":[{"ID":779389,"MetaID":774367},{"ID":779390,"MetaID":774367},{"ID":779387,"MetaID":774366},{"ID":779388,"MetaID":774366},{"ID":779386,"MetaID":774365},{"ID":779385,"MetaID":774364},{"ID":779384,"MetaID":774363},{"ID":779383,"MetaID":774362},{"ID":779382,"MetaID":774361},{"ID":779381,"MetaID":774360},{"ID":779378,"MetaID":774359},{"ID":779379,"MetaID":774359},{"ID":779377,"MetaID":774358},{"ID":779376,"MetaID":774357},{"ID":779375,"MetaID":774356},{"ID":779372,"MetaID":774355},{"ID":779373,"MetaID":774355},{"ID":779374,"MetaID":774354},{"ID":779370,"MetaID":774353},{"ID":779394,"MetaID":774370}],"playlistid":1461,"Title":"MX OPEN TALENT MARIA"}:
and as I made an ItemViewModel as ::
public class ItemEditViewModel
{
public long ID { get; set; }
public long MetaID { get; set; }
}
and My controller code is as::
[HttpPost]
public ActionResult Save(ItemEditViewModel[] data,long playlistid=0, string Title="")
{
for (int i = 0; i < data.Length; i++)
{
var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
if (pc == null)
{
pc = new PlaylistContent();
db.PlaylistContents.Add(pc);
}
pc.ContentMetaDataId = data[i].MetaID;
pc.PlaylistContentSequenceId = i + 1;
}
db.SaveChanges();
return Json(new { foo = "bar", baz = "Blech" });
}
while Execution of data in controller it doesn't accept the POSTED data as its ViewModel values.
My Problem is solved.
As I have Posted array in combination with two other variables, I just need to stringify array & not the whole ajax data which is to be posted.
as you can see in my code below::
var totaldata = { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {
alert("Playlist saved successfully!!");
}
})
In above code I have just done stringify on array & not on other data.
Thanks for some Co-operations of yours.

Resources