I upload a Html file with Dropzone.js, as into site examples :
//Upload view
#using System.Text;
#{
Layout = null;
string path = ViewBag.path;
}
#if (String.IsNullOrEmpty(fileName))
{
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/dropzone")
<form action="#Url.Action("Upload", "Home")" class="dropzone" id="dropzoneJsForm"></form>
<button id="submit-all">Submit All Files</button>
<script type="text/javascript">
Dropzone.options.dropzoneJsForm = {
//prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false,
init: function () {
var submitButton = document.querySelector("#submit-all");
var myDropzone = this; //closure
submitButton.addEventListener("click", function () {
//tell Dropzone to process all queued files
myDropzone.processQueue();
});
}
};
</script>
}
else
{
#Html.Raw(System.Web.HttpUtility.HtmlEncode(File.ReadAllText(path)))
}
//HomeController
public ActionResult Upload()
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
if (file.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
ViewBag.path = path;
}
}
return View();
}
The file was saved,the view can read it but the page did not display anything.
I can not figure out what's not working. If I active the debugger seems that everything is ok but in the end the page did not draw the html tag of the file. Can you help me or suggest a possible solution
Thank you so much
Instead HttpUtility.HtmlDecode, can you please check HttpUtility.UrlDecode, assuming your file is pure html, not html characters.
Related
I am using the filepond plugin to upload files in bulk. The uploaded files are saved to the cache. Now I want to click the delete button to delete the corresponding file on my cache. I want to know how the name or id of the front file should be transferred to the controller?
Or how the controller can get the filepond file when the form is submitted, it can also solve my current problem.
This is the code of the c#I use:
[HttpPost]
public ActionResult SaveFiles()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
UploadedFiles uploadedFiles = new UploadedFiles()
{
UserName = UserSession.CurrentUser.UserName,
PostedFile = file
};
uploadedFilesList.Add(uploadedFiles);
}
}
return Json(true);
}
[HttpDelete]
public ActionResult RemoveFile()
{
// How to put the id or name of the deleted file into this action?
return Json(true);
}
This is code of html and javascript I use
<div class="controls">
<input type="file" class="filepond" name="filepond" multiple
data-max-file-size="50MB" data-max-files="10">
<p class="help-block">Optional.</p>
</div>
<link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css" rel="stylesheet" />
<link href="https://unpkg.com/filepond/dist/filepond.min.css" rel="stylesheet">
<link href="https://unpkg.com/filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css" rel="stylesheet">
<script src="https://unpkg.com/filepond-plugin-file-encode/dist/filepond-plugin-file-encode.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-image-exif-orientation/dist/filepond-plugin-image-exif-orientation.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script>
FilePond.registerPlugin(
FilePondPluginImagePreview,
FilePondPluginImageExifOrientation,
FilePondPluginFileValidateSize
);
// Select the file input and use create() to turn it into a pond
FilePond.create(document.querySelector('.filepond'));
FilePond.setOptions({
server: {
process: '/List/SaveFiles',
revert: '/List/RemoveFile',
}
});
</script>
Normally, if you don't change anything in the Filepond revert settings, the file id will be sent as simple text in the request body. To get this id you will need to do something like this:
public async Task<IActionResult> OnDelete()
{
var fileId = "";
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
fileId = await reader.ReadToEndAsync();
}
bool isDeleted = false;
// Do delete your file
if (isDeleted)
return new ContentResult() { Content = "deleted" };
else
return new ContentResult() { Content = "error", StatusCode = 500 };
}
This is an ASP.NET Core version from a RazorPage
You should not use ActionResult.
[HttpDelete]
public string RemoveFile(int id)
{
return "Deleted!";
}
In my MVC application am allowing the user to upload PDF file and uploaded file gets saved in the folder. the file is getting uploaded correctly,but its not getting saved in the folder ...
View code is:
<a class="upload" onclick="upload(this);">
function upload(box) {
var box = dhtmlx.modalbox({
title: "Upload File",
text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' style='width: 86px' onclick='save_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 save_file(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter the URL");
return false;
}
dhtmlx.modalbox.hide(box);
dhtmlx.message("Uploading the file");
$.post("/FileUpload/UploadURL",
{ filename: '' + filename + '' });
}
Controller code is:
public ActionResult UploadURL(FormCollection data)
{
var filename=data["filename"];
SaveNewFile(filename);
return View();
}
public ActionResult SaveNewFile(string file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file) ?? "";
if (file.Length > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_fileUploadPath),
Path.GetFileName(file));
if (!System.IO.File.Exists(filePath))
{
filePath = Server.MapPath(_fileUploadPath + file);
TempData["UploadValidationMessage_Success"] = "File upload Succeeded.";
return View();
}
else
{
TempData["UploadValidationMessage_Failure"] = "File already exist.";
return View();
}
}
else
{
TempData["UploadValidationMessage_Failure"] = "Only PDF files are supported. Try again...";
return View();
}
}
You are not saving it. Just see the below post for how to save file:
File upload in MVC
For a complete tutorial: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
where in your code are you actually saving the file??? Try making use of
"HttpPostedFileBase" class.
Here's the sample Code
Use HttpPostedFileBase uploadFile parameter to accept Uploading file and SaveAs(filePath); to save!
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Also change your JQuery Post to Jquery Ajax post
$('form').submit(function(event) {
event.preventDefault();
var file = $("#filename").val();
file = file.serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: "/FileUpload/UploadURL",
data: file,
success: function( data )
{
alert( data );
}
});
return false;
}
</script>
first you need to tell the EncType for the form . Without encType file will not be posted to the server
<form action="" method="post" enctype="multipart/form-data">
</form>
for razor
#using (Html.BeginForm("Index", "yourCOntroller", FormMethod.POST, new { enctype = "multipart/form-data" }))
{
// some stuff
}
I have create web app in MVS 3
but failed to display alert message after data insert into database
Controller code:
[HttpPost]
public ActionResult QuestionBank(QuestionBank questionbank)
{
if (ModelState.IsValid)
{
dbEntities.QuestionBanks.AddObject(questionbank);
dbEntities.SaveChanges();
//questionbank.SendEnquiryEmail(questionbank);
ViewData["Message"] = "Data inserted";
return RedirectToAction("QuestionBank");
}
return View(questionbank);
}
Used ViewData["Message"] = "Data inserted"; which is not displayed message :(
whats going wrong or i placed it somewhere else?
OR ELSE I MAY HAVE THIS CODE
<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function () {
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= myvar %>";
if (bSuccess) {
alert("Successfully Inserted");
}
});
</script>
but i dont know where i declare that variable myvar which checks insertion plz help
On your .chsthml page:
<script type="text/javascript">
$(document).ready(function () {
var msg = '#ViewBag.Message';
alert(msg);
});
</script>
in your action:
ViewBag.Message = "1";
Edit: Apply conditional check in script:
<script type="text/javascript">
$(document).ready(function () {
var msg = '#ViewData["Message"]';
if(msg=='1')
alert("you are done with your thing");
});
</script>
In view:
ViewData["Message"] = "1";
ViewData["Message"] would result in same thing here.
Try to user
TempData
instead of
ViewData
I have the same issue
#using (Html.BeginForm("CreateRequest", "SupportRequest", FormMethod.Post, new { id = "frmStemplate", enctype = "multipart/form-data" }))
{
<td><input type="file" name="FirstFile" id="FirstFile" class="button" />
<input type="button" class="button" id="FirstFileupload" value="upload" onclick="Javascript:DocumentUpload();"/>
}
<script language="javascript" type="text/javascript">
function DocumentUpload()
{
var BrowseFile = $('#FirstFile').val();
if (BrowseFile != null && BrowseFile != "") {
alert(BrowseFile);
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Content("~/SupportRequest/UploadFiles")?fileElementId=' + BrowseFile,
success: function (data) {
alert('Hi'); //debugger;
if (data.Result == "SUCCESS") {
alert('Hi');
}
else {
ShowInfo('Document Uploaded Successfully');
}
}
});
}
}
</script>
On the controller side, I have:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFiles(string fileElementId, FormCollection formColl)
{
var FirstFile = Request.Files;
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(path, filename));
}
return Json(new { Filename = "" });
}
But my Request.Files is always null.
I tried several things, like changing the code to Request.Files["FirstFile"], etc. Each time, the file collection is empty.
You need to use HttpPostedFileBase in controller action parameters inorder to get the filedata that you have posted.
Please read this full article by Phil Haack
Since you are creating the post of the data you will need to post the file data. see this post:
How can I upload files asynchronously?
I did the different way using form collection that can easily Upload files.Like u did add that line inside begin form in cshtml page.
public ActionResult Create([Bind(Include="Id,Name,Pic,ActiveStatus")] FormCollection form)
{
string Pic = "";
var file = Request.Files[0];
if (file.ContentLength > 0)
{
Pic = string.Format("~/Uploads/Category/{0}", file.FileName);
file.SaveAs(HttpContext.Server.MapPath(Pic));
}
ItemCategory obj = new ItemCategory
{
Name = form["Name"].ToString(),
Pic = file.FileName
};
db.ItemCategories.Add(obj);
db.SaveChanges();
return RedirectToAction("Index");
Has anybody any help with using this control( http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ ) with ASP.NET MVC
I've tried, but in my controller the HttpPostedFile is always null.
Try
public ActionResult Upload(HttpPostedFileBase file) { ... }
in View <input type="file" name="file" id="file" />
<script type="text/javascript">
$("#formname").bind("submit", function () {
var ext = $('#file').val().split('.').pop().toLowerCase();
if (ext != "") {
if ($.inArray(ext, ['gif', 'png', 'bmp', 'jpg', 'jpeg']) == -1) {
alert('Invalid file extension!');
return false;
}
}
});
</script>
in Controller
public ActionResult Upload(HttpPostedFileBase file)
{
string fileName = "";
if (file != null)
{
if (file.ContentLength > 0)
{
fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string filePath = Path.Combine(HttpContext.Server.MapPath("~/FileFolder"), fileName);
file.SaveAs(filePath);
}
}
}