I was trying to get the base64 post in my codebehind webmethod,
but it seems like everytime I include the base64 I get an error : the server responded with a status of 500 (Internal Server Error) - it keeps on hitting the error function.
The Post works with the other strings when the base64 is not inlcuded int the data that im passing.
function event_create() {
alert("alert test : function works => onclick");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var eventTitle = $("#eventTitle").val();
var eventDesc = $("#eventDesc").val();
var eventTimeStart = $("#eventTimeStart").val();
var eventTimeEnd = $("#eventTimeEnd").val();
var eventDateStart = $("#eventDateStart").val();
var eventDateEnd = $("#eventDateEnd").val();
var eventType = $("#eventType").val();
var eventPlace = $("#eventPlace").val();
var eventAttendee = document.getElementById("lblSelected").innerText;
var userID = sessionStorage.getItem("userID");
var imageBase64 = getBase64(document.getElementById('test').files[0]);
var data = { 'eventTitle': eventTitle, 'eventDesc': eventDesc, 'eventPlace': eventPlace, 'eventType': eventType, 'eventAttendee': eventAttendee, 'userID': userID, 'imageBase64': imageBase64};
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: ".../../../../Operation/insert.aspx/createEvent",
data: JSON.stringify(data),
datatype: "json",
success: function (result) {
if (result.d <= 0) {
//false alert something
alert("FALSE");
}
else if (result.d > 0) {
//true
alert(result.d);
}
else {
alert("sent but no call-back");
}
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" connection to the server failed ");
console.log("error: " + errorthrown);
}
});
}
Here's the Webmethod that will get the post
[WebMethod(EnableSession = true)]
public static string createEvent(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string userID, string imageBase64)
{
String orgID = (String)HttpContext.Current.Session["orgID"];
string response = orgID;
string path = HttpContext.Current.Server.MapPath("~/Users/Organizer/organizerData/"); // de path
//Check if directory exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "event1" + ".jpg";// for instance
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
File.WriteAllBytes(imgPath, imageBytes); //write the file in the directory
return imageBase64;
}
Related
I am trying to call a webmethod in Ajax, And I want to get current login user id through session. How ever the HttpContext.Current.Session thrown System.NullReferenceException, how can I get the HttpContext.Current.Session. Here is my code.
function GetReportID() {
indicatorsIds = getSelectedIndicatorsIDs();
locationsIds = getSelectedLocationsIDs();
$.ajax({
type: "POST",
url: '<%= ResolveUrl("ChartEdit.aspx/GetIDForDownloadExcel") %>',
data: JSON.stringify({ ind: indicatorsIds, loc: locationsIds }),
contentType: "application/json",
dataType: "json",
success: function (data) {
//alert('Data: ' + data);
var data = JSON.parse(data.d)
console.log(data);
console.log(data.ClientID);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
And here is the WebMethod and Code.
public static string GetIDForDownloadExcel(string[] ind, string[] loc)
{
ChartEdit cd = new ChartEdit();
List<string> locationIDs = new List<string>(1024);
List<string> indicatorIDs = new List<string>(1024);
Guid clientID = Guid.NewGuid();
excelData.Ready = 0;
store.Add(clientID, excelData);
Thread thread = new Thread(() => cd.ExportToExcelDict(locationIDs, indicatorIDs,clientID));
thread.Start();
return JsonConvert.SerializeObject(new { ClientID = clientID, filename = "ExportToExcel" });
}
When it runs to the following code, NullReference Exception is thrown.
public static int GetCurrentUserId()
{
return Convert.ToInt32(HttpContext.Current.Session[FujiXerox.Common.Constants.KEY_NAME_CURRENT_USER_ID]);
}
I have an application where I want users to be able to upload and download their own files. I implemented the upload and download however I am concerned with XSS vulnerability of the download action. I was only able to implement the file actually downloading using GET method, but I want to secure it (usually I use POST + antiforgery token). How can I do this?
This is my controller action:
public ActionResult DownloadFile(int clientFileId)
{
var clientId = GetClientId(clientFileId);
var client = _unitOfWork.Clients.GetById(clientId);
if (client == null)
return HttpNotFound();
var file = _unitOfWork.ClientFiles.GetById(clientFileId);
if (file == null)
return HttpNotFound();
var practiceId = _unitOfWork.Users.GetPracticeIdForUser(User.Identity.GetUserId());
if (!AuthorizationHelper.CheckBelongsToPractice(_unitOfWork.Clients, typeof(Client),
practiceId, client.Id, nameof(Client.Id), nameof(Client.PracticeId)))
{
return new HttpUnauthorizedResult();
}
var fileInfo = new FileInfo(file.FilePath);
var fileName = fileInfo.Name;
if (!fileInfo.Exists)
return HttpNotFound();
var path = Path.Combine(Server.MapPath("~/ClientFiles/" + clientId + "/"), fileName);
var contentType = MimeMapping.GetMimeMapping(path);
try
{
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = false,
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(path, contentType, fileName);
}
catch (Exception ex)
{
new ExceptionlessLogger(ex).Log();
return new HttpStatusCodeResult(500);
}
}
And my ajax call
$('#client-files-table').on('click', '.js-download', function () {
var link = $(this);
$.ajax({
url: '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
method: 'GET',
//data: {
// __RequestVerificationToken: getToken()
//},
success: function () {
window.location = '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
loadPartials();
},
error: function () {
toastr.error('Unable to download.');
}
});
});
I found the answer here: https://codepen.io/chrisdpratt/pen/RKxJNo
$('#client-files-table').on('click', '.js-download', function () {
var link = $(this);
$.ajax({
url: '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
method: 'POST',
data: {
__RequestVerificationToken: getToken()
},
xhrFields: {
responseType: 'blob'
},
success: function (data, status, xhr) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
var header = xhr.getResponseHeader('Content-Disposition');
var filename = getFileNameByContentDisposition(header);
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
loadPartials();
},
error: function () {
toastr.error('Unable to download.');
}
});
});
I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}
I am trying to send the 'file' attachment to handler(and send it with email)
This is the code I am using to send it to handler(JS)
When I debug it I see the right values including the file(debug in java-script).
function sendCv_click() {
var settings = {
'data': getData("sendCv"),
'url': "Handlers/SendCV.ashx",
'contentType': 'false',
'processData': 'false'
};
sendCV(settings);
};
function getData(){
data = {
'fullName': $('#txt_sendCv_fullName').val(),
'cvFile':$('#fu_sendCv_upload')[0].files[0],
'email': $('#txt_sendCv_email').val(),
'checkBox': $('#sendCv_chkBox:checked').length
}
function sendCV(settings) {
$.ajax({
type: "POST",
contentType: settings.contentType,
processData: settings.processData,
data: settings.data,
url: settings.url,
dataType: "json",
success: function(data) {
...
},
error: function(data, xhr) {
...
});
}).always(function() {
...
});
}
}
How can I get them in the handler page?
like that I get them as Null, why?
public void ProcessRequest(HttpContext context)
{
string fullName = context.Request.Form.Get("fullName"); //It's Null
string email = context.Request.Form.Get("email");//It's Null
string chkBox_ad = context.Request.Form.Get("checkBox"); //It's Null
/////how can i get the file here ??
bool mailSent = Mail.SendCV(fullName, email, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
This might work...
var postedFile = context.Request.Files[0];
var parser = new MultipartParser(context.Request.InputStream);
if (parser.Success) {
byte[] content = parser.FileContents;
string filename = parser.Filename;
}
MultipartParser is opensource class - see http://multipartparser.codeplex.com/SourceControl/latest#MultipartParser.cs
I have following method and i need to deserialize the retrieve stream.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val= JsonSteamToString(jsonString);
}
public string JsonSteamToString(Stream jsonStream)
{
StreamReader reader = new StreamReader(jsonStream);
return reader.ReadToEnd();
}
My class is as follows:
public class H2JsonStateObject
{
public string url { get; set; }
public string stateId { get; set; }
}
I'm calling this method using Ajax call as follows:
var value ="89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9";
var link="RedirectPage.aspx";
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
var jsonToSend = JSON.stringify(data);
$.ajax({
cache: false,
url: "StateRedirectService.svc/RefreshPagemethod",
type: "POST",
async: false,
data: jsonToSend,
success: function (data, textStatus, jqXHR) {
window.location.href = link;
},
error: function (xhr, status, error) {
alert('error');
}
});
When the request receive to web method and after converting the value it get following string.
"\"{\\\"url\\\":\\\"RedirectPage.aspx\\\",\\\"stateId\\\":\\\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\\\"}\""
Now i need to deserialize url & stateId. How can i do that?
I tried followings. but couldn't able to deserialize.
Using DataContractJsonSerializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(val)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(H2JsonStateObject));
H2JsonStateObject p2 = (H2JsonStateObject)deserializer.ReadObject(ms);
}
It throws exception and says :
Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
Using JavaScriptSerializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Object obj = serializer.DeserializeObject(val);
This gives me my object as string value as follows:
"{\"url\":\"RedirectPage.aspx\",\"stateId\":\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\"}"
What I did wrong and how can i get RedirectPage.aspx and 89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9 value?
Able to solve this problem in following way. my problem is with Json string value.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val = JsonSteamToString(jsonString);
string JsonVal = val.Replace("\"", "'");
var json_serializer = new JavaScriptSerializer();
H2JsonStateObject myobj = json_serializer.Deserialize<H2JsonStateObject>(JsonVal);
H2RequestRedirect.RedirectToTemp(myobj.url, myobj.stateId);
}
in here string needs to be in following format.
JsonVal = "{'url': 'RedirectPage.aspx','stateId': '89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9' }";
When i'm calling this method i send json object without JSON.stringify(data);
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
$.ajax({
cache: false,
url: "StateRedirectService.svc/RedirectHyperlink",
type: "POST",
async: false,
data: data,
success: function (data, textStatus, jqXHR) {
//alert('OK');
window.location.href = link; },
error: function (xhr, status, error) {
alert('error');
}
});
Then it works as a charm...