How to get the last modified date of the uploaded file? - javascript

I upload an XML file to migrate its contents to my database, but I want firstly store the last modified date of that file to assure that no change has happened to that file from the last one.
How do I get the last modified date of the file ?
Is there any javascript function to do that?

This information is never sent to the server when you use a file input to upload a file. Only the filename, mime type and contents are sent with multipart/form-data. You could use the HTML5 File API to obtain this information from the file before uploading it.
As requested in the comments section here's an example of an ASP.NET page which has an upload control and a hidden field which will be used to store and send the file last modified date to the server using the HTML5 File API:
<%# Page Language="C#" %>
<%# Import Namespace="System.Globalization" %>
<script type="text/C#" runat="server">
protected void BtnUploadClick(object sender, EventArgs e)
{
var file = Request.Files[0];
DateTime date;
if (DateTime.TryParseExact(lastModifiedDate.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// you could use the date here
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<label for="up">Pick a file</label>
<asp:FileUpload ID="up" runat="server" />
<asp:HiddenField ID="lastModifiedDate" runat="server" />
<asp:LinkButton ID="btnUpload" runat="server" Text="Upload" OnClick="BtnUploadClick" />
</form>
<script type="text/javascript">
if (!window.File) {
alert('Sorry, your browser doesn\'t support the File API so last modified date will not be available');
} else {
document.getElementById('<%= up.ClientID %>').onchange = function () {
if (this.files.length > 0) {
if (typeof this.files[0].lastModifiedDate === 'undefined') {
alert('Sorry, your browser doesn\'t support the lastModifiedDate property so last modified date will not be available');
} else {
var lmDate = this.files[0].lastModifiedDate;
var hidden = document.getElementById('<%= lastModifiedDate.ClientID %>');
hidden.value = lmDate.getFullYear() + '-' + (lmDate.getMonth() + 1) + '-' + lmDate.getDate();
}
}
};
}
</script>
</body>
</html>
So in this example we subscribe for the onchange event of the file input and if the client browser supports HTML5 File API we can obtain information about the selected file such as its name, size, last modified date, ... In this example we store the last modified date into a hidden field so that this information is available on the server once we upload the file.

System.IO.FileInfo object should yield a LastWriteTime property
FileInfo myFileInfo= new FileInfo(path) ;
myFileInfo.Refresh();
string t = myFileInfo.LastWriteTime.ToString("F")

Related

How can I save edited JSON file to web server using JSONEditor?

I'm using the JSONEditor (https://github.com/josdejong/jsoneditor) to load a json file, make changes and save the file. This works great but it only saves the JSON file to the folder specified according to your browser settings. Here's the demo code (https://github.com/josdejong/jsoneditor/blob/master/examples/04_load_and_save.html):
<!DOCTYPE HTML>
<html>
<head>
<title>JSONEditor | Load and save</title>
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<script src="https://bgrins.github.io/filereader.js/filereader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<style>
html, body {
font: 11pt sans-serif;
}
#jsoneditor {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<h1>Load and save JSON documents</h1>
<p>
This examples uses HTML5 to load/save local files.
Powered by FileReader.js and
FileSaver.js.<br>
Only supported on modern browsers (Chrome, FireFox, IE10+, Safari 6.1+, Opera 15+).
</p>
<p>
Load a JSON document: <input type="file" id="loadDocument" value="Load"/>
</p>
<p>
Save a JSON document: <input type="button" id="saveDocument" value="Save" />
</p>
<div id="jsoneditor"></div>
<script>
// create the editor
var editor = new JSONEditor(document.getElementById('jsoneditor'));
// Load a JSON document
FileReaderJS.setupInput(document.getElementById('loadDocument'), {
readAsDefault: 'Text',
on: {
load: function (event, file) {
editor.setText(event.target.result);
}
}
});
// Save a JSON document
document.getElementById('saveDocument').onclick = function () {
// Save Dialog
fname = window.prompt("Save as...");
// Check json extension in file name
if(fname.indexOf(".")==-1){
fname = fname + ".json";
}else{
if(fname.split('.').pop().toLowerCase() == "json"){
// Nothing to do
}else{
fname = fname.split('.')[0] + ".json";
}
}
var blob = new Blob([editor.getText()], {type: 'application/json;charset=utf-8'});
saveAs(blob, fname);
};
</script>
</body>
</html>
I want to be able to save the file to the web server. Is there any way for me to save the edited JSON file to the web server? I searched and tried to integrate this library with JSONEditor but no joy:
https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
I'm not restricted to ajax so I'll consider anything that works!
Thanks for your advice.
John
UPDATED: Here's the controller code chunk.
// POST api/values
public async void Post()
{
string json = await Request.Content.ReadAsStringAsync();
File.WriteAllText(
HttpContext.Current.Server.MapPath("~\\App_Data\\somefile.json"),
json
);
}
I tested this using Postman and it works. What I can't seem to do for the life of me is to now send the edited JSON file to the controller. Here's the modified HTML page where I try unsuccessfully to send the json. For brevity, I'll just add the extra/edited code code:
<form id="form1" method="post" enctype="text/plain" action="http://localhost:1651/api/values">
<input type="file" name="json" id="loadDocument" value="Load"/>
<input type="submit" value="Save" />
</form>
Edited javascript where I try to return the edited json to the form:
document.getElementById('saveDocument').onclick = function () {
return editor.getText();
};
Please help! How do I send the json to the controller?

How to get file name from asp:FileUpload and display in a Label using ASP.NET and C#

I am using a <asp:FileUpload> to upload a PDF file to my web page. But after clicking on browse the window opens, and once I select a file and click on Open i want to get the file name and display it in a Label. What function should I use in ASP.NET to do this? I tried the OnLoad, OnUnload, OnDataBinding, etc. in the <asp:FileUpload> but nothing works. Can someone suggest me a solution for this?
My code is as below:
<asp:FileUpload ID="fileUpload" runat="server" /><br />
<asp:Label ID="labelFilename" runat="server" Text=""></asp:Label>
Once I select a file and click open the file name should be displayed in the label.
You can use this code:
<script>
$(document).ready(function () {
$('#fileUpload').change(function () {
var path = $(this).val();
if (path != '' && path != null) {
var q = path.substring(path.lastIndexOf('\\') + 1);
$('#labelFilename').html(q);
}
});
});
</script>
You can access the file name(server side) by using following code snippet
string file_name=fileUpload.FileName.ToString();
You can access the filename on client side using following code snippet
$(document).ready(function () {
$("#fileUpload").change(function () {
var FileUpload = $("#fileUpload").val();
... }
}

How can I use Ajax to update data in two different input type forms without it clearing information from the other?

I am creating a webpage which will allow users to upload their own images and create a collage, to which they will be able to add a title and (eventually) save/retrieve by title.
I am currently using Ajax to handle setting the image as background using the JS below:
function setUploadedBackground(fileName){
var ajx;
if (window.XMLHttpRequest)
{// If the browser if IE7+[or] Firefox[or] Chrome[or] Opera[or]Safari
ajx=new XMLHttpRequest();
}
else
{//If browser is IE6, IE5
ajx=new ActiveXObject("Microsoft.XMLHTTP");
}
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
//change background
}
}
ajx.open("GET","index.jsp",true);
ajx.send();
return false;
}
The form "uploadAction" uses the following action jsp to actually upload and save files.
<form id= "uploadForm" action="
<%# page import="java.io.*,java.util.*, javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.io.output.*" %>
<%
int uploadFailed = 0;
File file ;
String fileName = null;
int maxFileSize = 500000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
//if (contentType.indexOf("multipart/form-data") >= 0) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("uploads/"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("ISO-8858-2");
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator iter = fileItems.iterator();
while ( iter.hasNext () ) {
FileItem fi = (FileItem)iter.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName().replaceAll("\\s", "");
String mimeType = getServletContext().getMimeType(fi.getName());
if(mimeType == null) mimeType = fi.getContentType();
if (mimeType.startsWith("image")) {
String command = "update users set mm11='"+fileName+"' where name = 'Gjeta'";
st.executeUpdate(command);
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
}
else {
file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
else uploadFailed = 2;
}
}
} catch(Exception ex) {
System.out.println(ex);
if(ex.toString().contains("IOFileUploadException")) uploadFailed = 1;
}
//}
%>"
method="post" enctype="multipart/form-data">
<input class="uploads" type="file" name="file" size="50"/>
<input class="uploadFile" type="submit" value="Upload File"/>
<script type="text/javascript">
<% if (uploadFailed == 0) { %>
setUploadedBackground('<%=fileName%>');
<% } else if (uploadFailed == 1) { %>
alert("Maximum file size exceeded");
<% } else if (uploadFailed == 2) { %>
alert("Please upload an image");
<% } %>
</script>
</form>
My problem is that doing this erases the data in the other form which I use to allow users to input and update the collage title. The code for this is here:
<form id = "nameBoardForm" method="post">
<input type='text' name='collageName' id='collageNameInput' />
<input type='submit' name='submit' id='submitBtn' value="Save collage" class='enableOnInput' disabled='disabled' />
</form>
To update the title using Ajax, I use the JS
$( "#nameBoardForm" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize().replace(new RegExp("\\+", "g"), ' ') );
updateTitle($( this ).serialize().replace(new RegExp("\\+", "g"), ' '));
});
I know that the problem is that when uploading a file, the upload form essentially redirects to an action page, and although I use Ajax to set the uploaded image as the background of the container div, the fact that I am not using something like
event.preventDefault();
means that the form submit causes a redirect, as far as I understand. I have tried using the same kind of logic as my nameBoardForm uses, ie, using jQuery to change what happens on submit but I cannot get the file name parameter I need using serialize() because this just seems to return an empty string for the file input form (even though it works perfectly for the text input form)
Is there any way I can get around this? At the moment if a user uploads an image, it is set as the div background, and then they can also change the collage title from 'Untitled' to their own collage name, using Ajax, without affecting the uploaded image/background of the div. However, if a user sets the name of the collage first, then when an image is uploaded and set to background, the collage title is reset to 'Untitled' thus the user loses the data they have already input...
Eventually the idea is that I will save the filename to a database under the collage title so that users can then search for collages by titles they have used before and have a collage redisplayed based on images they previously uploaded. However, this means that the data input to the collage title is crucial and so cannot be erased by Ajax setting an image as the div background - any advice? I have been googling for a solution for ages but it seems file input forms are weird, and I haven't found anything useful.
EDIT-----------------------
The resulting HTML is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing</title>
<script src="js/jquery-1.8.1.min.js" type="text/javascript" language="javascript"></script>
<script src="js/setUploadedBackground.js" type="text/javascript" language="javascript"></script>
<script src="js/enableButton.js" type="text/javascript" language="javascript"></script>
<!--script src="params.js" type="text/javascript"></script-->
<link href="css/newstyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3 id="title"><div class="collageTitle">Untitled</div></h3>
<form id = "nameBoardForm" method="post">
<input type='text' name='collageName' id='collageNameInput' />
<input type='submit' name='submit' id='submitBtn' value="Save collage" class='enableOnInput' disabled='disabled' />
</form>
<div id="uploadsContainer" class="mm11Container" style="top:100px; left: 300px;">
<div id="img" class="mm11 card front face">
<form id= "uploadForm" action=""
method="post" enctype="multipart/form-data">
<input class="uploads" type="file" name="file" size="50"/>
<input class="uploadFile" type="submit" value="Upload File"/>
<script type="text/javascript">
<% if (uploadFailed == 0) { %>
setUploadedBackground('<%=fileName%>');
<% } else if (uploadFailed == 1) { %>
alert("Maximum file size exceeded");
<% } else if (uploadFailed == 2) { %>
alert("Please upload an image");
<% } %>
</script>
</form>
</div>
</div>
<script src="testing.js" type="text/javascript"></script>
</body>
</html>

Getting session value in javascript

I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);

Saving javascript variable in server side variable (vbscript)

I know you cant save javascript variables into server side variables (vbscript) directly, but is there a way around this like saving java script variables into html hidden inputs then using javascript to post. Is this possible? If not what else can i do? Below is my code so far get the value of a drop down list - javascript
function selectedDatabase() {
select_temp = form1.elements["selection"];
select_index = select_temp.selectedIndex;
select_text = select_temp.options[select_index].text;
}
Below is the HTML code
<center><select id="selection" onchange="selectedDatabase()">
<option>Movies</option>
<option>Movies 2</option>
<option>New Movies</option>
<option>New Movies 2</option>
</select></center>
</td></tr>
What you're looking for is called ajax. You can do it manually, or better use a JavaScript library such as MooTools, jQuery, or Prototype.
Check out Google University's Ajax tutorial. I would avoid w3schools' tutorials.
Just to cover all the bases, why can't you just have the user submit the form?
Also, you could do this with cookies, though you won't get the cookie values on the server until the next GET or POST from the user.
It is Possible to store javascript variable values into server side variable. All you have to do is to implement "System.Web.UI.ICallbackEventHandler" class.
Below is the code demonstrating how to do it.
In aspx Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Calback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb=document.getElementById("tbxPassword");
var product=lb.value;
CallServer(product,"");
}
function ReceiveServerData(rValue){
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="password" id="tbxPassword" />
<input type="Button" onclick="LookUpStock">Submit</button>
</div>
</form>
</body>
**
In Code Behind (CS) Page
**
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference
(this,"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
if(eventArgument == null)
{
returnValue = "-1";
}
else
{
returnValue = eventArgument;
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
Now you can get the JavaScript variable "product" value into Server side variable "returnValue".

Categories

Resources