I am trying to pass some JavaScript variable value from .aspx file to .ashx file when user uploads a document in the web form.
The web form is a .aspx file and the uploading functionality is in .ashx file. So I need to pass the variables from .aspx file to .ashx file.
I was able to pass three variables but when I try to pass the fourth one then it does not work. It does not give any error but just do not pass any of the variables. When I debug the code I can see the debugger does not enters the process of upload. And the upload button also changes
This is my .aspx page code.
<%# Page Title="" Language="VB" MasterPageFile="~/_resx/E4.master" AutoEventWireup="true" CodeFile="new.aspx.vb" Inherits="E4_Jobs_new" ValidateRequest="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<script type="text/javascript">
var id = '<%= ModeID%>', mode = '<%= Mode%>', employer = '<%= Employer.Name %>', jtitle = document.getElementById(<%= txtTitle.ClientID%>);
</script>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtTitle" Display="None" ErrorMessage="xx" ValidationGroup="NewJob" EnableViewState="False" />
<div class="form-element">
<input type="text" id="txtTitle" runat="server" maxlength="64" /></div>
<div class="m-accor-body">
<ul id="attachmentList">
<% For Each additionalDoc As DataRow In Vacancy.Attachemnts.Rows%>
<li id="da<%= additionalDoc.Item("id") %>">
<span><%= additionalDoc.Item("name") %></span>
<span class="rd" data-did="<%= additionalDoc.Item("id")%>"> remove</span>
</li>
<%Next%>
</ul>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file">
</div>
</asp:Content>
And this is the code in the .aspx file where I am passing the variables into .ashx file
$(function () {
dimNav('vacancy');
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jtitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
}
});
});
The first three variables values are obtained differently than the fourth one. In the fourth one I used javascript function to get the value (as it is the input value given by the user. Not a value stored already in database. ) .
This is my code for in the upload-job-attachments.ashx file where I retrieve the values
Public Class upload_job_attachments : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
context.Response.Expires = -1
Try
Dim Id As Integer = CInt(context.Request("draftid"))
Dim type As String = CStr(context.Request("type"))
Dim empname As String = CStr(context.Request("employer"))
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
********** other lines of code ***********
End Sub
End Class
what can I do to overcome the problem. I am weak in advanced javascript functionalities. I appreciate your help
Addition
The whole script looks like
$(function () {
dimNav('vacancy');
var jobTitle = $('#' + '<%= txtTitle.ClientID%>').val();
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jobTitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
alert($('#' + '<%= txtTitle.ClientID%>').val());
}
});
$('body').on('click', '.rd', function () {
var el = $(this);
$.post('delete-job-attachment.ashx?id=' + el.attr('data-did'), '{}', function () {
$('#da' + el.attr('data-did')).remove();
});
});
$('.price-button').click(function () { $(this).next('.price-list').fadeToggle('slow'); });
$('.m-lists table tr:nth-child(4) td:nth-child(1)').prepend('<div>Multiple job posting</div>');
$('.jMedias').change(function () {
suffleMedias();
});
var suffleMedias = function () {
var mids = [];
$('.jMedias:checked').each(function () {
mids.push($(this).val());
});
$('.mediaLists').val(mids.toString());
};
$('.jType').change(function () {
suffleJobType();
});
$('input:radio.p-option-radio').change(function () {
var pOption = $(this).val();
$('.p-option').val(pOption);
});
var suffleJobType = function () {
var type = $('.jType').val();
if (type == 0) {
$('#contractLength, #jobHour').slideUp();
} else if (type == 1) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 2) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 3) {
$('#contractLength, #jobHour').slideDown();
}
};
var suffleFeeType = function () {
var fType = $('.feeType').val();
if (fType == 0) {
$('#salaryRateMax, #salaryRateMin, #agencyFee').slideDown();
} else if (fType == 1) {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
$('#agencyFee').slideDown();
} else if (fType == 2) {
$('#agencyFee').slideUp();
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
};
$('.feeType').change(function () {
suffleFeeType();
});
$('.referrerPercentage').change(function () {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
$('#salaryRateMax, #salaryRateMin').slideDown();
} else {
if ($('.feeType').val() == 1) {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
});
$('.calcFee').change(function () {
CalculateAndDisplayFees();
});
$('.rAgency').chosen().change(function () {
if ($(this).val() != '-1') {
$('.psls').val('-1').trigger("liszt:updated");
$('.retained').val('1');
}
});
$('.psls').chosen().change(function () {
if ($(this).val() != '-1') {
$('.rAgency').val('-1').trigger("liszt:updated");
$('.retained').val('0');
}
});
var setPublishOption = function () {
var p = $('.p-option').val();
var $radios = $('input:radio.p-option-radio');
$radios.filter('[value=' + p + ']').attr('checked', true);
};
suffleJobType();
suffleFeeType();
suffleMedias();
CalculateAndDisplayFees();
setPublishOption();
});
If, for instance, the jtitle field needs to come from an input control, you can do:
'formData': {
'jtitle': $("#somecontrol").val()
}
Which will get the value from a control. Is that what you mean?
Related
Im Stuck with the problem that I can't get the "UploadMultiple" to work.
Whenever I try to Drop more than one File at once (drag and dropp 3 selected PDF files for example) I don't recieve any files in the c# controller.
The View seems to work, as there are no errors when dropping the Files.
In the controller however, I don't recieve any files (files.Count = 0).
these are my code snippets:
View HTML:
<div class="col-md-8">
<form id="fileUploadForm" class="text-center dropzone needsclick dz-clickable" method="post" enctype="multipart/form-data" style="min-height: 500px;">
</form>
</div>
JS:
Dropzone.autoDiscover = false;
$("#fileUploadForm").dropzone({
url: "/UploadView",
paramName: "files",
uploadMultiple: true,
parallelUploads: 1,
maxFilesize: 50,
init: function () {
this.on('success', function (file) {
var element = document.getElementById("submitbutton");
element.style.display = "inline";
var args = Array.prototype.slice.call(arguments);
var lowercaseName = file.name.toLowerCase()
if (!lowercaseName.includes(".pdf") && args[1] === "success") {
$("#directUploadDocs").append("<p>" + file.name + "</p><br />");
} else {
switch (args[1]) {
case "HashFailed":
$("#errorDocs").append("<div><h4>CUSTOM_TEXT</h4><p>" + file.name + "</p></div>");
break;
case "UnknownFile":
$("#errorDocs").append("<div><h4>CUSTOM_TEXT</h4><p>" + file.name + "</p></div>");
break;
case "success":
console.log("success");
break;
default:
console.log("sorry an error happened");
}
}
});
},
});
C# Controller:
public async Task<IActionResult> OnPostAsync(ICollection<IFormFile> files)
{
var directoryPath = Path.Combine(_appSettings.UploadFolder, user.SessionID);
Directory.CreateDirectory(directoryPath);
foreach (var file in files)
{
var uploadPath = Path.Combine(_appSettings.UploadFolder, user.SessionID, Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
if (file.Length > 0)
{
Do Something;
}
}
return Content("success");
}
I know that I wrote pretty custom code additional to the reccomended code from dropzone.js, but I hope its still possible to fix that Problem.
SOLVED!
SOLUTION:
Bruce Adams Posted an answer that actually worked for me:
new C# controller:
public async Task<IActionResult> OnPostAsync()
{
var directoryPath = Path.Combine(_appSettings.UploadFolder, user.SessionID);
Directory.CreateDirectory(directoryPath);
foreach (var file in Request.Form.Files)
{
var uploadPath = Path.Combine(_appSettings.UploadFolder, user.SessionID, Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
if (file.Length > 0)
{
Do Something;
}
}
return Content("success");
}
I have the following downloadZip.html. The download works in Chrome and Edge, but not in IE. This file gets called as below from jspf page. When I click "Download listed documents" it call popupDownloadWindow(), which will open downloadZip.html in plainview. This html when loaded calls enableLink() and the flow goes. As the view is plainview, only first if block of enableLink() is executed (if(callerview == "plainview")). Not sure if this is happening because of setTimeout(). Please help me here. Let me know for any information.
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
setTimeout("checkReturn()",500);
//setTimeout(function() {
// checkReturn();
//}, 500);
}
Complete code:
<script>
var downloadZipChildWindow;
function popupDownloadWindow(){
downloadZipChildWindow = window.open('../html/downloadZip.html?view=plainview','downloadwindow','width=300,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
}
</script>
<a id='download_link' class='download_link' href="#" onClick="popupDownloadWindow()">Download listed documents</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download documents as Zip file</title>
<script type="text/javascript" src="../js/jquery-1.6.1.min.js" ></script>
<style type="text/css">
p
{
font-family:"Verdana";
font-size:small;
}
a
{
font-family:"Helvetica";
font-size:small;
}
</style>
<script type="text/javascript">
var lastParam;
var sessionsNotOk = "DEF";
var callerView;
function getParam( paramName )
{
paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+paramName+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/*
* Checks the return from ajax servlet call "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs".
* Called always right after checkDocbaseSessions() call.
*/
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
//setTimeout("checkReturn()",500);
setTimeout(function() {
checkReturn();
}, 500);
}
function enableLink(){
callerView = getParam("view");
var pkgType = "";
var params = "";
var packageIDs = "";
if (callerView == "plainview") {
pkgType = window.opener.$('#hiddenPkgType').attr('value');
// Check available sessions
if (pkgType == 'srp'){
document.getElementById('dlink').style.display='none';
document.getElementById('checkSession').style.display='inline';
document.getElementById('checkSession').style.textAlign='center';
document.getElementById('checkSession').style.display='';
packageIDs = window.opener.$('#hiddenSRPIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
}
params = window.opener.$('#hiddenDownloadParams').attr('value');
} else if (callerView == "packagedetailview") {
pkgType = window.opener.$('#hiddenPkgType_DetailedPackageView').attr('value');
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_DetailedPackageView').attr('value');
} else if (callerView == "SRP_packagedetailview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_DPV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_DetailedPackageView').attr('value');
} else if (callerView == "SRP_checkstatusview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_CSV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_CheckStatusView').attr('value');
}
if (pkgType == 'nlp' || pkgType == 'monnlp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_country').style.textAlign='center';
document.getElementById('download_zip_stdfilenames_nlp_product').style.textAlign='center';
document.getElementById('download_zip_stdfilenames').style.display='none';
} else if (pkgType == 'clp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
} else if (pkgType == 'ipl') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
}
//Defined as global
zipParamsImp = params + "&filename=import";
zipParamsStd = params + "&filename=standard";
}
function showIndicator(param){
document.getElementById('divIndicator').style.display='inline';
document.getElementById('divIndicator').style.textAlign='center';
document.getElementById('divIndicator').style.display='';
document.getElementById('dlink').style.display='none';
var parameters = "";
if (param == 'import'){
parameters = zipParamsImp;
} else if (param == 'standard') {
parameters = zipParamsStd;
} else if (param == 'standard_nlp_country') {
parameters = zipParamsStd + "_nlp_country";
} else if (param == 'standard_nlp_product') {
parameters = zipParamsStd + "_nlp_product";
}
lastParam = param;
postwith("../downloadzip",parameters);
}
function postwith (to, params) {
var myForm = window.opener.document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
myForm.style.display = 'none';
jQuery.each(params.split('&'), function(){
var pair = this.split('=');
var myInput = window.opener.document.createElement("input") ;
myInput.setAttribute("name", pair[0]) ;
myInput.setAttribute("value", pair[1]);
myForm.appendChild(myInput);
});
var lastInput = window.opener.document.createElement("input") ;
lastInput.setAttribute("name", "download_token_value_id") ;
lastInput.setAttribute("value", "");
myForm.appendChild(lastInput);
window.opener.document.body.appendChild(myForm) ;
myForm.submit();
window.opener.document.body.removeChild(myForm) ;
//setTimeout("checkProgress()",1000);
setTimeout(function(){
checkProgress();
},1000);
}
/*
* Checks return from servlet call "../downloadzip?ask=isready" -> ask whether DownloadAsZipServlet
* has finished its work or not. If finished, close this popup.
*/
function checkProgress(){
window.focus();
$.ajax({
type: "GET",
url: "../downloadzip?ask=isready",
dataType: "text",
//dataType: "script",
//timeout: 2000,
success: function(results)
{
// Normal flow
//var result = eval('('+results+')');
var currParams = window.opener.$('#hiddenDownloadParams').attr('value');
//After closing DPV and clicking on Download Listed Documents button, we have to remove caller param, because there is no caller.
//Caller exists only if openPackage function called, and Download is on a DPV page.
//If we do not remove caller param, then exception occurs.
var callerPrefix = currParams.substring(0,currParams.indexOf('&'));
if (callerPrefix.indexOf('caller=') > -1) {
window.opener.$('#hiddenDownloadParams').attr('value',currParams.replace(callerPrefix+'&',""));
} else {
// No caller param found
}
if (results.indexOf('window.close()') > -1) {
window.close();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
/*
* In case of SRP - checks whether sessions for all required docbases are available.
* It is needed, because SRP package documents can be located in different docbases.
*/
function checkDocbaseSessions(pIDs){
sessionsNotOk = "DEF";
$.ajax({
type: "GET",
url: "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs,
dataType: "text",
success: function(results)
{
//alert(results);
if ($.trim(results) == 'OK'){
//alert("Sessions are OK!");
sessionsNotOk="OK";
} else {
sessionsNotOk=results;
//alert("Sessions are NOT OK! - "+sessionsNotOk);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
</script>
</head>
<body style="background-color: #ffffff; font-family: Verdana, Helvetica; font-size: x-small;" onload="enableLink();">
<div id="divIndicator" style="display: none"><br />
<p>Zip file creation in progress. This may take a few minutes, please wait and do not navigate away or start another query!</p>
<br />
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
<br />
</div>
<p style="text-align: center">Download listed documents</p>
<div id="dlink" style="text-align: center">
With import file names
<br />
With standard file names
With standard file names starting with country
With standard file names starting with product
</div>
<div id="noSession" style="display: none">
<p>Some required sessions are unavailable. Please login to the docbase!</p>
</div>
<div id="checkSession" style="display: none">
<p>Checking required sessions in progress. Please wait...</p>
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
</div>
</body>
</html>
Using CKEditor to send email and upload attachments. Below is the minimal configuration I've from this source.
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = $(response).html();
$closeButton = $('<span class="attachment-close">').text('x').on('click', closeButtonEvent)
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html(attachment).append($closeButton))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
}
}
});
On the Controller side I've got below code
const string scriptTag = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}')</script>";
public ContentResult UploadAttachment()
{
string basePath = HttpContext.Server.MapPath("~/assets/Images/");
const string baseUrl = #"/ckfinder/userfiles/";
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return BuildReturnScript(funcNum, null, "No file has been sent");
if (!System.IO.Directory.Exists(basePath))
return BuildReturnScript(funcNum, null, "basePath folder doesn't exist");
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return BuildReturnScript(funcNum, null, "File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = System.IO.Path.Combine(basePath, sFileName);
//Note: you may want to consider using your own naming convention for files, as this is vulnerable to overwrites
//e.g. at the moment if two users uploaded a file called image1.jpg, one would clash with the other.
//In the past, I've used Guid.NewGuid() combined with the file extension to ensure uniqueness.
receivedFile.SaveAs(nameWithFullPath);
var url = baseUrl + sFileName;
return BuildReturnScript(funcNum, url, null);
}
private ContentResult BuildReturnScript(int functionNumber, string url, string errorMessage) {
return Content(
string.Format(scriptTag, functionNumber, HttpUtility.JavaScriptStringEncode(url ? ? ""), HttpUtility.JavaScriptStringEncode(errorMessage ? ? "")),
"text/html"
);
}
Below is the response I get back inside onAttachmentUpload - function
<form enctype="multipart/form-data" method="POST" dir="ltr" lang="en" action="/Controller/UploadAttachment?CKEditor=email_Message&CKEditorFuncNum=0&langCode=en">
<label id="cke_73_label" for="cke_74_fileInput_input" style="display:none"></label>
<input style="width:100%" id="cke_74_fileInput_input" aria-labelledby="cke_73_label" type="file" name="attachment" size="38">
</form>
<script>
window.parent.CKEDITOR.tools.callFunction(98);
window.onbeforeunload = function({
window.parent.CKEDITOR.tools.callFunction(99)
});
</script>
But it is expecting some data-id for attachment id. I've no idea what the response should look like. Could someone tell me what the actual response should look like and what is the data-id its expecting as attr in response? Also, is there anyway I can upload multiple files with this?
This is how I am returning the response now and rendering the attached file. Hope it might help someone in future.
[AcceptVerbs(HttpVerbs.Post)]
public ContentResult UploadAttachment() {
string basePath = HttpContext.Server.MapPath("~/somepath");
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return Content("No file has been sent");
if (!System.IO.Directory.Exists(basePath))
Directory.CreateDirectory(Path.Combine(basePath));
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return Content("File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = Path.Combine(basePath, sFileName);
receivedFile.SaveAs(nameWithFullPath);
var content = "<span data-href=\"" + nameWithFullPath + "\" data-id=\"" + funcNum + "\"><i class=\"fa fa-paperclip\"> </i> " + sFileName + "</span>";
return Content(content);
}
and on the JS side I have below code to append the uploaded file name:
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = response;
$closeButton = '<span class="attachment-close btn btn-danger float-right" style="margin-top:-7px"><i class="fa fa-trash"></i></span>'; //.on('click', closeButtonEvent)
$respDiv = '<ol class="breadcrumb navbar-breadcrumb" style="padding:18px 15px"><li style="display:block">' + attachment + $closeButton + '</li></ol>';
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html($respDiv))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
$('.ticket-attachment-container').on('click', '.attachment-close', function() {
$(this).closest('.ticket-attachment').remove();
if (!$('.ticket-attachment-container .ticket-attachment').length)
$('.ticket-attachment-container').hide();
});
}
}
});
This is my Get action method to get posts with their image:
public JsonResult GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
PostedByName = post.ApplicationUser.UserName,
PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
and this is my GetFileData action method to retrieve the images from the database:
public FileResult GetFileData(int fileId)
{
var file = db.Files.Single(x => x.FileId == fileId);
return File(file.Content, file.ContentType);
}
and this is the method which will generate url:
private string _GenerateAvatarUrlForUser(int? Id)
{
var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == Id);
if (avatarImage != null)
return Url.Action("GetFileData", new { fileId = avatarImage.FileId });
return String.Empty;
}
and this is the view page to show the user name with their pic but i am not able to show pic:
<div>
<div id="ajaxDiv">
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
var div = $('#ajaxDiv');
div.html("<br /> " + "Users received from server: " + "<br />");
$.each(data, function (i, item)
{
printUser(div, item);
});
});
});
function printUser(div, item)
{
div.append("<br/>" + "UserName: " + item.PostedByName + "<br/>" + "Pic: " + item.PostedByAvatar);
// I am stuck here on how to append image to this div or how to pass item.PostedByAvatar to this img src tag
div.append("<img src= + item. />");
<img src="#Url.Action("GetFileData", "Home", new { id = item.Id })" style="width:100px;height:100px;"/>
}
</script>
the url which i am successfullly getting back is like this:
/Post/GetFileData?fileId=2
how to resolve this ???
In your GetFileData action the parameter name in fileId. But when you are setting the source of image you are using the parameter name id which should be fileId like below.
#Url.Action("GetFileData", "Home", new { fileId = item.Id })
Update: As you said this should work.
div.append('<img class=cssClassName src="' + item.PostedByAvatar +'"/>');
Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);