Load a JSON file from user input [duplicate] - javascript

This question already has an answer here:
Reading local files with <input type="file">? [duplicate]
(1 answer)
Closed 8 years ago.
I want to get and read a JSON file that would be uploaded by the user.
I created the html input file:
<div id="button_open" class="button">
<span>Open a JSON file</span>
<input id="input_open" class="input_file" type="file">
</div>
And now, I don't know how to load the data from the file. I only can get the filename.
Here is what I wrote:
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange(e) {
var filname = $("#input_open").val();
var fileContent = ... ?
var jsonData = JSON.parse(fileContent);
}
Anyone knows how to get the file content?

<script>
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange(e) {
var filname = $("#input_open").val();
var fileContent = getTxt();
var jsonData = JSON.parse(fileContent);
}
getTxt = function (){
$.ajax({
url:'text.json',
success: function (data){
fileContent =data;
return data
}
});
}
</script>

Here is the solution I get with the help of Ameen:
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange() {
var filePath = $("#input_open").val();
var startIndex = filePath.indexOf('\\') >= 0 ? filePath.lastIndexOf('\\') : filePath.lastIndexOf('/');
var filename = filePath.substring(startIndex);
if(filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
$.ajax({
url: filename,
success: onOpenLoad
});
}
function onOpenLoad(fileContent) {
var data = JSON.parse(fileContent);
// do something with the data
}

Related

Why I cannot open a CSV file using JQuery and FileContentResult

I'm trying to make an ajax call (I specifically don't want to do it using ActionLink).
I'm having a controller that is like this:
public IActionResult ExportUsers(List<string> listOfEmails)
{
/*some data processing*/
return File(result, "text/csv", "ExportCandidates.csv");
}
On the other side with ajax I do this simple call:
$.ajax({
url: '/Admin/Testcenter/GenerateInvitationPreview',
type: 'post',
data: {
//some input data to send to the controller ​
​},
​success: function (response) {
​)
​}
​});
I know there exists something for pdf files where you return a base64 file and with the response in the ajax call you just write something like pdfWindow.document.write(...) and this will open a new window with a pdf file.
Is there a way to extract the response for my CSV file and generate it so the user downloads it ?
USE NPOI Library for Excel Sheet Generation
//Generate Excel Sheet
try
{
Guid gid = Guid.NewGuid();
string ext = ".xls";
string[] Headers = { "Appointments Id", "Date of Appointment", "Doctor Name", "Patient Name", "Visit Type", "Status" };
string fileName = "AppointmentsExcelSheet_" + gid.ToString() + ext;
var serverpath = _env.ContentRootPath;
string rootpath = serverpath + "/wwwroot/ExcelSheets/" + fileName;
FileInfo file = new FileInfo(Path.Combine(rootpath, fileName));
var memorystream = new MemoryStream();
using (var fs = new FileStream(rootpath, FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Appointments List");
IRow row = excelSheet.CreateRow(0);
var font = workbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)FontBoldWeight.Bold;
for (var i = 0; i < Headers.Length; i++)
{
var cell = row.CreateCell(i);
cell.SetCellValue(Headers[i]);
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
}
var result = _Appointment.GetAppoinmentsPDf();
int index = 1;
foreach (var app in result.Items)
{
//var PatientDob = Convert.ToDouble(app.PatientDOB);
row = excelSheet.CreateRow(index);
row.CreateCell(0).SetCellValue(app.AppointmentId);
row.CreateCell(1).SetCellValue(app.DateofAppointment+" "+app.TimeofAppointment);
row.CreateCell(2).SetCellValue(app.DoctorFullName);
row.CreateCell(3).SetCellValue(app.SelectedPatientName);
row.CreateCell(4).SetCellValue(app.PurposeofVisit);
if (app.IsActive == false)
{
row.CreateCell(5).SetCellValue("Inactive");
}
else
{
row.CreateCell(5).SetCellValue("Active");
}
index++;
}
workbook.Write(fs);
}
using (var filestream = new FileStream(rootpath, FileMode.Open))
{
filestream.CopyToAsync(memorystream);
}
memorystream.Position = 0;
//send filepath to JQuery function
response.Msg = "/ExcelSheets/" + fileName;
}
catch (Exception Ex)
{
//exception code
}
return Ok(reponse.Msg)
//JavaScript
function AppointmentsExcelSheet() {
//var token = Token;
//var link = path;
debugger
$.ajax({
//'Content-Type': 'application/pdf.',
type: "GET",
url: "/api/Appointments/GetAppointmentsExcelSheet",
beforeSend: function () {
$.blockUI({
message: ('<img src="/images/FadingLines.gif"/>'),
css: {
backgroundColor: 'none',
border: '0',
'z-index': 'auto'
}
});
},
complete: function () {
$.unblockUI();
},
success: function (data) {
debugger
//downloads your Excel sheet
window.location.href = data.msg;
}
});
}
The best way to do what you want to do is to not use AJAX, but use either a link click that opens a new window (since you are passing in parameters) If you could use a
<form target="_blank">
to open a form response. Inside the form can be a field or fields that contains the list of emails (it can be one field, or multiple input fields with the same name). Your action handler can accept that list, parse it, and return a File response, and the natural result of opening the new window from the form post operation is a file that opens up.

JSON get data form url using javascript and than save the data to a var [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
<script type="text/javascript">
$(document).ready(function() {
var chanName = "";
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//MAKE IT TO A VAR
});
}
function loadChannel(data) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
}, 5000);
$('#update').click( function(){
loadchannelID($('#chnlName').val());
})
});
</script>
This is what is have done so far. I need to get the id form a Youtube channel but i have a Youtube name. So i need to convert the name to the youtube channel id. The "Function loadchannelID" is what i have so far, it works but i need to get the #ytID to a var. But I dont know how to do that. The other function is to show the data from the Channel ID and that will work aswell if the id is converted to a var. Please help! Thanks!
I hope this is what you want to achieve:
var chanName = "";
var chanID = 0;
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
chanID = data.items[0].id;
$('#ytID').html(chanID);
loadChannel(chanID); // now, you know the ID, pass it to "loadChannel"
});
}
function loadChannel (id) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
I am not clear if you are trying to get the value or you try to make the url but in both cases you can do:
if you want to get the param value you can use:
var url_string = "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=Pewdiepie&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI";
var url = new URL(url_string);
var forUsername = url.searchParams.get("forUsername");
if you want to set the param you can do:
var forUsername = url.searchParams.set("forUsername", yourValueHere);
As ive already said, your code is async, so you may use Promises like this:
function loadchannelID(name){
return new Promise(function(resolve){
var chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//lets resolve the promise
resolve(data.items[0].id);
});
});
}
So you can use it like this:
loadChanelID("test").then(function(name){
alert("name is"+name);
});
If you change
function loadChannel(data) {
To:
function loadChannel(id){
You can do:
loadChanelID("test").then(loadChannel);
I assume you want to use your var within the class and chanName is your channel ID and name container array
(function($, jsYouTube){
var chanName = "";
$.getChannelID = function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$this.chanName['id'] = data.items[0].id ;
});
}
})(jQuery, 'jsYouTube');

MVC Jquery file upload Request.Files is always empty

I have been searching online looking for the answer to this problem but I cannot seem to find anything that works, I have the following Controller code:
[HttpPost]
public ActionResult UploadFiles()
{
// If files exist
if (Request.Files != null && Request.Files.Count > 0)
{
// ** Do stuff
return Json(new { result = true, responseText = "File(s) uploaded successfully" });
}
// Return no files selected
return Json(new { result = false, responseText = "No files selected" });
}
And following code in my cshtml page which works fine and the controller can see the files that I upload:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Quotes/QuoteFiles/UploadFiles", false);
xhr.send(fileData);
}
</script>
However when I try and change this to work using an Ajax call as shown below then Request.Files in the Controller always has no files. The only bit I have changed is the "Send files to controller" part:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
$.ajax({
url: '/Quotes/QuoteFiles/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);
}
});
}
</script>
I am running this in Google Chrome but I have tried IE 11 and Edge but not of them work. Can anyone tell me what I am doing wrong?
try using a fileReader instead of a formData and change the mimetype to 'text/plain; charset=x-user-defined-binary'
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example_Uploading_a_user-selected_file
I have finally found what was causing this issue, I have the following code on my _Layout.cshtml page which is there to automatically send the AntiForgeryToken on any ajax requests I make, this appears to be causing the problem because once I remove it Request.Files is not empty. I now need to see if I can find a way to add this code back in where it will not stop file uploads working:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
});
});
**** EDIT ****
I have now reworked this as shown below to add 'if(opt.data != "[object FormData]"' which resolves the issue by not calling the code if it is a file upload:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
// If not "FormData" (i.e. not a file upload)
if (opt.data != "[object FormData]")
{
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
}
});
});

Upload file data from input of type file in a form using javascript and jquery

I have a from with input of type file I need to get the file data from this form without refreshing the page
I'm try to use this function
function submitForm(form){
var url = $(form).attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
but this function get the values of form inputs, but I need to get all file data (tmp_name, file_name, file_type ...)
so can any one help me in this please
thanks in advance
Maybe you can reference your input of type file by id and then get the files property to obtain information about the files.
Then you can loop through the files and for example read the name, size and type attribute of the File object.
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
https://developer.mozilla.org/en-US/docs/Web/API/File
For example
$("#theForm").submit(function(e) {
submitForm(this);
e.preventDefault();
});
function submitForm(form) {
var url = $(form).attr("action");
var formData = {};
formData.filesInfo = [];
var files = $('#inputFile').prop("files");
$(files).each(function() {
var fileInfo = {};
fileInfo.name = this.name;
fileInfo.size = this.size;
fileInfo.type = this.type;
formData.filesInfo.push(fileInfo);
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="theForm">
<input type="file" id="inputFile">
<input type="submit" name="submit" id="submit">
</form>

HTML5 File Handeling in JavaScript?

What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>

Categories