How to upload File from URL - asp.net-mvc

In my application am allowing the user to upload file from the URL
code to upload File URL:
function loadURL(box) {
var box = dhtmlx.modalbox({
title: "Load URL",
text: "<div id='form_in_box'><div>Enter the URL of PDF file <hr/><input type='text' name='files' id='files' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Load URL' style='width: 86px' onclick='load_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
})
}
function load_file(box) {
var file = document.getElementById('files');
if (file == "") {
alert("Enter File URL");
return false;
}
file = file.value;
var filename = file.substring(file.lastIndexOf('/') + 1);
dhtmlx.modalbox.hide(box);
$.post("/FileUpload/UploadURL",
{ file: '' + file + ''
});
}
Controller code
public ActionResult UploadURL(string file)
{
string files = Path.GetFileName(file);
string myStringWebResource = "";
WebClient myWebClient = new WebClient();
myStringWebResource = file;
string path = Server.MapPath(_fileUploadPath + files);
myWebClient.DownloadFile(myStringWebResource, path);
string extFile = Server.MapPath(_fileUploadPath + files);
return View();
}
Files are gettinig downloaded successfully. Now I want to upload the same file How can I do so?

HTML file upload control is for uploading from client's computer only. What you have to do is to download file from another server and save it at yours. This thread should help.

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.

uploading file using input field

I created a web app using asp.net-mvc and Jquery
when I added the below code my application automatically stop running without throwing any error, I don't know Whether it is my visual studio 19 or IIS which is being crashed
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
To verify I created an asp.net mvc sample project and paste the above code in the index page but the same problem comes
Image
what can I do to solve this?
Do you have
enctype="multipart/form-data"
property in your form element?
<form id="upload">
<input type="file" id="file" class="form-control">
</form>
Jquery
$('#upload').submit(function (e) {
e.preventDefault(); // stop the standard form submission
var File_Name = $("#file").prop('files')[0].name;
var ext = File_Name.split('.').pop();
if (ext == "pdf" || ext == "docx" || ext == "doc" || ext == "png" || ext ==
"jpg" || ext == "jpeg" || ext == "txt") {
var lastIndex = $("#file").prop('files')[0].name.lastIndexOf(".") + 1;
var form = new FormData();
form.append("file", $("#file").prop('files')[0]);
$.ajax({
url: '/Main/SaveDocument',
type: 'POST',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
if (data == "999") {
swal("Note", "Some Error Occurred. File Not uploaded successfully.", "error");
}
},
error: function (xhr, error, status) {
console.log(error, status + " " + xhr);
}
});
}
else {
swal("Note", "File Type Not Supported.", "warning");
}
});
C#
public ActionResult SaveDocument()
{
//file
var file = System.Web.HttpContext.Current.Request.Files["file"];
var CheckCnic = hr_FTPEntities.File_description.Where(x => x.uploader_CNIC == userCNIC).FirstOrDefault();
if(CheckCnic == null)
{
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
if (filebase.ContentLength > 0)
{
var fileName = Path.GetFileName(filebase.FileName);
string path = Path.Combine(Server.MapPath(basePath + departmentName) + "/");
File_description file_Description = new File_description();
int fileCount = hr_FTPEntities.File_description.Select(x => x).ToList().Count + 1;
int lastIndexOfDot = fileName.LastIndexOf(".") - 1;
string finalFileName = fileName.Substring(0, lastIndexOfDot) + "_" + fileCount + fileName.Substring(lastIndexOfDot + 1);
file_Description.file_name = finalFileName.ToString();
try
{
filebase.SaveAs(path + (finalFileName));
}
catch(Exception ex)
{
return Json("999");
}
}
return Json("000");
}
else
{
return Json("888");
}
}
You could try to use the below code:
View(Index.cshtml) :
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', 'test');
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Controller (HomeController.cs):
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Make sure your IIS site contains the upload folder and enough permission to access the folder.
If you still face the same issue then try to use the different browser.
check event viewer logs or try to collect the dup and analyze the dump using the DebugDiag tool.

sending form data xmlhttprequest

In below code first am allowing the user to select the option from the drop down list and than allows to browse the file.
Code:
function choice() {
var box = dhtmlx.modalbox({
text: "<div id='form_in_box'><div>Choose a File to Convert <hr/><label>Filename: <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Create PDF' style='width: 86px' onclick='Convert(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
function Convert(box) {
var ch = document.getElementById('choice');
var file = document.getElementById('file');
if (file.value == "") {
alert("Choose a file to convert");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Convert', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('File successfully conveted to PDF');
}
};
xhr.send(fd);
}
In ch the drop down option gets saved.
I want to send ch value to the controller
Controller code:
public ActionResult Convert(HttpPostedFileBase file, FormCollection data)
{
string choice = data["choice"];
how can i send it?
You could add it to the FormData:
var fd = new FormData();
fd.append('file', file.files[0]);
fd.append('choice', ch.value);
and your controller action may now look like this:
public ActionResult Convert(HttpPostedFileBase file, string choice)
{
...
}

How to save images/shapes in PDF file

In my application am allowing the user to create PDF file. Also the user can add shapes(like rectangle, line),, form fields (textarea, checkbox..) in the PDF file. when user clicks on save button PDF gets created successfully but the shapes and form fields that user has included in his document doesn't appear.
function create_PDF(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter filename");
return false;
}
var content = CKEDITOR.instances["message"].getData();
if (content == "") {
alert("Enter Content in The Editor");
return false;
}
content = content.trim();
dhtmlx.modalbox.hide(box);
dhtmlx.message("Saving file...");
$.post("/FileUpload/CreateNewPDFile",
{
filename: '' + filename + '', content: '' + content + ''
}, function (data) {
alert("PDF File created succesfully");
CKEDITOR.instances["message"].setData("");
CKEDITOR.instances["editor1"].setData("");
});
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult CreateNewPDFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".pdf");
htmlContent = htmlContent.Trim();
htmlContent = htmlContent.Replace("<p>", "\n").Replace("</p>", "\n");
Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
if (!System.IO.File.Exists(sFilePath))
{
Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
doc.SetMargins(50, 50, 50, 50);
doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
PdfWriter.GetInstance(doc, new System.IO.FileStream(sFilePath, System.IO.FileMode.Create));
iTextSharp.text.Font fnt = FontFactory.GetFont("Times New Roman", 14);
doc.Open();
PdfPTable pdfTab = new PdfPTable(1);
PdfPCell pdfCell = null;
pdfCell = new PdfPCell(new Phrase(new Chunk(htmlContent)));
pdfTab.AddCell(pdfCell);
doc.Add(pdfTab);
doc.Close();
Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Write(doc);
Response.Flush();
Response.End();
}
return View();
}
If use includes textarea , rectangle and checkmark in the newly created PDF instead of textarea, rectangle and checkmark the following thing appears how can i avoid this code and can display on the respective images in the document

Error in saving CKEDITOR content

In my application am allowing the user to create PDF file. Have used CKEDITOR in my application.
function create_PDF(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter filename");
return false;
}
var content = CKEDITOR.instances["message"].getData();
if (content == "") {
alert("Enter Content in The Editor");
return false;
}
content = content.trim();
dhtmlx.modalbox.hide(box);
dhtmlx.message("Saving file...");
$.post("/FileUpload/CreateNewPDFile",
{
filename: '' + filename + '', content: '' + content + ''
}, function (data) {
alert("PDF File created succesfully");
CKEDITOR.instances["message"].setData("");
});
}
CreateNewPDFFile controller code is:
public ActionResult CreateNewPDFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".pdf");
htmlContent = htmlContent.Trim();
if (!System.IO.File.Exists(sFilePath))
{
Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
doc.SetMargins(50, 50, 50, 50);
doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
PdfWriter.GetInstance(doc, new System.IO.FileStream(sFilePath, System.IO.FileMode.Create));
iTextSharp.text.Font fnt = FontFactory.GetFont("Times New Roman", 14);
doc.Open();
PdfPTable pdfTab = new PdfPTable(1);
PdfPCell pdfCell = null;
pdfCell = new PdfPCell(new Phrase(new Chunk(htmlContent)));
pdfTab.AddCell(pdfCell);
doc.Add(pdfTab);
doc.Close();
Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Write(doc);
Response.Flush();
Response.End();
}
return View();
}
PDF file gets created successfully but the displays HTML content in it
for example: If i have inserted radio buttons in the file than in newly created file it displays
<input name="age" type="radio"
value="15-20" />
and not the radio buttons.
How can I avoid html content ?

Resources