I have an Image variable loaded in a JavaScript app, and I want to pass it to a C# method in my ASP.NET app (so I can store it in a database). The only problem I am having is getting the image's data itself to the C# method. I tried using an AJAX call (it's a GET) with the C#'s method's byte[] parameter set to the Image's .Picture, but the byte[] is empty.
How do I get the image's data from the JavaScript script to the C# method?
UPDATE:
I tried copying the image to a canvas using drawImage on the canvas's rendering context, but the image has to come from my local computer, so when I subsequently try to call canvas.toDataURL, it throws a DOM Security error.
I also considered using FileReader to get the data directly rather than loading it as an image, but, for political reasons, I have to support browsers that don't implement FileReader yet.
Am I asking for something that just isn't possible in JavaScript? (There must be a way of doing this (not necessarily in JS), as Facebook implements loading images from the client computer's local file system.)
I don't know how you load your image in javascript app. But when i faced the same issue , i did it in the follwing way.
HTML
<input id="imgInput" type="file" name="file" />
<img id="imagePreview" src="" alt="Item Image" width="96" height="80"/>
<input id="Button1" type="button" value="save image" onclick="saveimage();"/>
JS
$(document).ready(function () {
$("#imgInput").change(function () {
readURL(this);
});
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
function saveimage() {
var images = $('#imagePreview').attr('src');
var ImageSave = images.replace("data:image/jpeg;base64,", "");
var submitval = JSON.stringify({ data: ImageSave });
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
datatype: "json",
data: submitval,
url: "your url",
success: function (data) {
//code for success
}
});
}
.CS
[WebMethod]
public static string saveimage(string data) {
byte[] imgarr = Convert.FromBase64String(data);
/* Add further code here*/
}
Related
I took a HTML string from tinyMCE and wrapped it with jQuery html(). I am now trying to unwrap it and display it in the the view.
I get tinyMCE contents and put them into to a div. I then extract html contents of that div and pass it to my database via AJAX. I am now trying to convert the contents back into format that will allow me to display it properly.
<textarea name="tinycontent" class="form-control"
id="textFromContentEditor" value=""></textarea>
<div id="textContent" style="display:none"></div>
var sectionContent = tinyMCE.activeEditor.getContent();
sectionContent = $('#textContent').text(sectionContent).html();
$.ajax({
url: '/Home/CreateNoteContent',
async: false,
type: 'POST',
data: {
headerID: headerID,
categoryID: categoryID,
sectionContent: sectionContent
},
success: function (result) {
if (result == false) {
toastr.error("Cannot create new content")
} else {
toastr.success("Successfully created new content")
$("#feed-" + releaseID).trigger('click');
jumpTo(scrollPos);
}
}
});
My input into tinyMCE: Hello World
What gets stored in the db: <p>Hello World</p>
I want to be able to display just the text contents in the view.
I am certainly not very good at js, ajax and so on, but this is what I did in my project to display html in one of my divs from the pages -tag.
var blobs = document.getElementById('your-div-Id').innerHTML = "<h4>somethingRandom</h4>";
OBS! I believe this is javascript and therefor might not be the right solution.
Hope this helps!
I'm trying to parse html page that have link which loads additional data to current page.
<a href="#" data-href="/some-url/">
There a javascript function that calls after clicking on <a href="#">.
I'm able to parse data that already loaded with page, but can't parse additional block that loads by click on <a>. How can I parse all of the data including post-load data using AngleSharp?
JS code:
$('.button_add a').click(function (e) {
e.preventDefault();
var link = $(this);
var page = link.data('page');
$.ajax({
method: 'get',
url: link.data('href'),
data: {page: page},
success: function(data) {
var linkParent = link.parent();
var parentBlock = linkParent.parent();
parentBlock.children('.items').first().append(data.view);
}
});
});
Make sure to allow AngleSharp to load JS files.
var config = Configuration.Default
.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true })
.WithJs();
Keep in mind that AngleSharp.Js may not be able to deal with the complexity of the given script. Check the debug output for any exceptions.
I have an
<input type="file" name="uploadedFile">
Model:
public HttpPostedFileBase UploadedFile { get; set; }
Uploading works fine, but in my "UploadedFile" after postback, there is always just the last upload.
I need to upload multiple files without selecting them all at once.
I know there is multiple="multiple" that you can add as attribute for the input, but there I would need to select all files at once.
Tried a List, no luck.
So what I need is:
Click Upload button. file prompt opens, select an image, click open, file prompt closes.
Repeat Step 1 choose another Image. No Postback has happened yet.
Send the form/do a post. Both Images should be available in the controller
Currently I just receive the second image.
Anyone can help me with this?
Kind Regards
never tested it but i think this should work for you
<input type="file" id="texboxID" name="uploadedFile[]">
Add File
<script>
function addFiles(){
$("#myForm").append('<input type="file" name="uploadedFile[]" />')
}
</script>
then uploading should be something like this:
function UploadFilesToServer(texboxID) {
var fileUpload = $("#" + texboxID+"").get(0);
var files = fileUpload.files;
var FilesToServer = new FormData();
for (var i = 0; i < files.length; i++) {
FilesToServer.append(files[i].name, files[i]);
}
$.ajax({
url: "url",
type: "POST",
contentType: false,
processData: false,
data: FilesToServer,
// dataType: "json",
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
hope i understood your question and answered you in a convenient way
you can store the selected files in FileList Array , then use this array to upload the files
html :
<input type="file" id="fileUpload">
jQuery:
$(document).ready(function(){
var fileArray=[];
$("#fileUpload").change(function(e){
var upFile = e.target.files[0];
fileArray.push(upFile);
console.log(fileArray);
});
})
I have tested the array it works fine , but I didn't test it in backend
I have a base image, and I use C# Graphics library to add data to it, and then return the image converted to byte array.
I have a controller:
public ActionResult DisplayDR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}
That works fine with,
<img id="drImage" src="#Url.Action("DisplayDR")" width="1110" height="484" alt="qr code" />
I need to be able to dynamically update the image and attempted with ajax with no luck.
Using:
function getNewDRImage(instance) {
var drNum = $(instance).data('val');
var src = '#Url.Action("DisplayDR", "Home", new { area = "Part" })';
$.ajax({
type: "GET",
url: src,
data: { drNum : drNum },
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (err) {
var msg = "Client side error, " + err;
throwClientSideErrorMsg(msg)
},
success: function (data) {
$('#drImage').attr("src", data.image);
}
});
}
and returning JSON like so,
public JsonResult DisplayDMR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return
Json(new { image = File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png") }, JsonRequestBehavior.AllowGet);
}
Gives me this error:
System.Web.HttpException (0x80004005): The controller for path '/[object Object]' was not found or does not implement IController.
What am I not doing correctly?
update, viewing the source after the ajax call I see why the error occurs, as this is what the response is:
<img id="dmrImage" src="[object Object]" alt="qr code" height="484" width="1110">
So I guess I am confused on what to do with the JSON data to update the image.
With your ajax code you're trying to load actual bytes of your image and assign that to the src attribute. That's not what the attribute expects.
All you need is to just assign a new image url as a string. The browser then will automatically fetch actual bytes and show the new image for you.
If you want to use the same url for the updated image you need to make sure the browser won't use your old cached image. Take a look at this answer for how to do this.
To add Cache-Control: header to your File() response use Response.AddHeader() method:
public ActionResult DisplayDR(int drNum)
{
Response.AddHeader("Cache-Control", "no-store");
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}
I have an ajax post request:
function downloadElevationMap() {
var jsonData = ko.toJSON(mod.SelectedItem);
$.ajax({
url: '/Home/GetData/',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: jsonData,
success: function (data) {
console.log("OK");
},
});
}
The controller method recive data correct. The code is presented below:
public FileStreamResult GetData(Mv jsonData)
{
var resultAll = jsonData.Data.Select(d => d.y).ToList();
var str = new StringBuilder();
_fileName = "ses"+jsonData.Path;
foreach (var d in resultAll)
{
str.Append(d + " ");
}
var byteArray = Encoding.ASCII.GetBytes(str.ToString());
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", string.Format("{0}.txt", _fileName));
}
Mv - is my class that represent data. When debug the both str and stream variable contain correct data.
Function downloadElevationMap() is called by onclick="downloadElevationMap()"
I just want when downloadElevationMap() is called the GetData controller return a file for download. But simply nothing happend. Where the error is?
well you dont need ajax to do that try this
window.location="download.action?para1=value1...."
for your needs you can do some thing like this
window.location="/Home/GetData/?"+$.param(jsonData )
I'm fairly sure what you are doing is swallowing the data in the success callback in the AJAX call - all your code will do is download the file, call the success callback, and then just print "OK" to the console.
As Anto said, you don't need AJAX (and, indeed, should not be using AJAX) for this. His answer is absolutely correct, provided you can use a GET string. If you need to use a POST request, create a form with hidden inputs and submit that - something like:
HTML
<form action="/Home/GetData" method="POST" id="dataToSubmit">
<input type="hidden" name="param1" value="value1" />
<input type="hidden" name="param2" value="value2" />
<input type="hidden" name="param3.param4" value="value3" />
</form>
JS
function downloadElevationMap() {
// Write code to map your jsonData to your form elements
$('#dataToSubmit').submit();
}
You could make the form dynamically if you wish. You might be able to update your page to post directly with a submit button.
One final note, you don't need to submit the data as Json. If you have
{
"param1": "value1",
"param2": "value2",
"param3": {
"param4": "value3"
}
}
then if you just use the format in the form above, it will submit fine - this reference explains how to submit to deep models.