ASP.net and HTML File Upload - javascript

Problem: I'm working on a site written with a master page and a wrapper form. The page I'm writing needs to upload a file to the server to be validated.
What's needed: A way to submit a file without using a form and receive that form on the server in a WebMethod.
What I've tried: Using an XMLHttpRequest to send FormData to a WebMethod. The FormData is created and the file is appended like so:
let dataXML = new FormData();
dataXML.append("xml", $("#fileUpload")[0].files[0]);
sent it like this:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
// Do stuff with the request.responseText
};
request.open("POST", PageName + "/" + Route, true);
request.send(dataXML);
with a webMethod like this:
[WebMethod]
public static string myWebMethod(MultipartFormDataContent Files)
{
// Do stuff with the file
}
The WebMethod does not run at all. I'm assuming this is an issue with the WebMethod and its parameters. If I look at Page_Init() (which is run because it's returning the pages html right now rather than running my WebMethod) I can see the file in HttpContext.Current.Request.Files[0] but I don't know how to make the WebMethod run.
And before anyone says it: yes, I tried JQuery AJAX but it doesn't make a difference, the problem doesn't appear to be client side (the file was uploaded in both cases). I don't really care between JQuery AJAX and XMLHttpRequest.

Related

Reading JavaScript Variables in PHP

I am looking for a way to either read an image src in PHP or read a JavaScript variable in PHP.
The plan:
I have a webcam script in JavaScript that takes an image using the base64 Canvas method, but I need it to update a MySQL record using PHP.
After trying many methods; cookies, submit forms, ajax. I decided that making a post here was the best idea.
(!) Use with caution. This is a proof of concept. In PHP you should never just accept and compute client-side data without checking it for malicious code and sanitizing the input. (!)
You could send it to PHP using AJAX by putting your base64-source into formData.
Javascript:
// ajax.js
var xhr = new XMLHttpRequest(); // initialize a new XHR
var formData = new FormData(); // initialize form data
var myFile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEaElEQVR4Xu3UgQkAMAwCwXb/oS10i4fLBHIG77YdR4AAgYDANViBlkQkQOALGCyPQIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJ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YLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiDwAIGUVl1ZhH69AAAAAElFTkSuQmCC';
xhr.open('POST', '/requestHandler.php') // init your request
xhr.onreadystatechange = function () {
// check if the server was able to compute the XHR
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// handle the response
console.log(xhr.responseText) // log the PHP output
}
}
// a form data element needs a descriptor/name and a value.
formData.append('myfile', myFile);
xhr.send(formData); // send your xhr to the server
PHP:
// requestHandler.php
<?php
if('$_POST') {
echo $_POST['myfile']; // this is your image source
}
Further information:
XMLHttpRequest
FormData
PHP $_POST

uploading pdf/doc etc and sending data to the server in request - Javascript

I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript.
I was thinking to do with Blob , byte stream .. is it possible.
Can someone explain ?
Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.
Some questions to consider when you are working doing this:
Are you looking to upload just the file or do you need to upload any associated data with it?
Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it.
What server/framework are you using? How do you access this? A request object? Something similar?
How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
Do you need to support CORS? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.
file input that allows multiple file support
<input type='file' id='multiple-file-input' multiple>
javascript example
// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to
var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';
var formdata = new FormData(); // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable
// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {
// Appending each file to FormData object
// sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);
}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr); // log response object
}
}

Upload a file through a webpage to mySql database?

I have a HTML webpage with a form to upload a file. When you click submit I want to send the form to a php file where it will store it in my database.
Currently I use the reqular xmlHTTPRequest to send a GET request to my php files. This all works perfectly so I would prefer not to restructure my program.
Could someone give me some guidance as to how to do that? I tried to send the file as I sent other inputs (Text etc) but got a null value in the php.
Code:
The HTML is a simple input tag (this won't show it when I copy it in).
JavaScript:
var picture = document.getElementById("file").value;
generateAjaxRequest("type=insert&picutre="+picture")
AJAX:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange= function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(elementName).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/Controller.php);
xmlhttp.send();
PHP:
$file = #$_GET["file"];
$query = mysqli_prepare($conn, "INSERT INTO table (image) VALUES (?)");
mysqli_stmt_bind_param($query, 's',$file);
stmtGetInfo($query);
When a file is uploaded a user will click submit which will call the Javascript. The javascript sends the file to the ajax which then sends it to the php file. I have only put up some of the code to demonstrate what is happening. All of the methods work for text entry etc.
If you are trying to upload files using xmlHTTPRequest, these links can be usefull.
https://gist.github.com/ebidel/2410898
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Websocket form handling

I'd like to send JSON form data to websocket server instead of submitting the form and reload the page.
In AJAX it is pretty simple and straightforward thanks to native FormData() web-api object:
myform.addEventListener("submit",function(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onload = myFormHandler.bind(xhr);
xhr.open('POST',myform.action,true);
xhr.send(new FormData(myform));
}
It would be nice to have similar functionality in webSockets, to transform the form data into JSON object and use it like this:
myWebSocket.omessage = myFormHandler;
myform.addEventListener("submit",function(e) {
e.preventDefault();
myWebSocket.send(JSONformData);
}
But the reference (see the link above) says that FormData has only append method, I don't know how to send the form data to the websocket server and extract them there.
On code.google.com I've found something very close to what I need: form2js but it can't handle files (it can be done using FileReader.readDataAsURL). Should I add the file handling functionality into that code, or is there any native solution like FormData object?

Why is my code failing to pass parameters from JavaScript to JSP using XMLHttpRequest?

I am trying to write JavaScript code which, on a mouse click event, sends some parameter (id) to the server-side JSP code. The JSP code then returns a string to the JavaScript.
...and the response text will be a string returned from JSP specified in out.println(substring);.
This code is not working. Sorry if I am doing something silly; I am new to coding for the web.
XMLHttpRequest is an asynchronous request by default, meaning that after you call send, the next line of code is executed before the request has finished. The code to be executed when the request finished goes into your "state change" handler. You're already assigning a state change handler here:
xmlHttp.onreadystatechange = handleRequestStateChange
But you never define what handleRequestStateChange actually is. You should probably read about ready states and the onreadystatechange event.
Try the following code instead:
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
This code assigns to handleRequestStateChange a function which will be called when the ready state of the XMLHttpRequest changes. The function checks to see if the ready state is 4 (request finished and response is ready) and if so, the you will be able to access the responseText property of the request which will contain the response from the JSP page.
As a suggestion for the future, when you've learned how AJAX request work, you may find a helper library like jQuery makes tasks like this much easier!
In your case (GET method) you need to pass the variables in the open method directly (at the end of the url)
xhr.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xhr.send(null);
Goyuix's technic is only correct in the case of the POST method:
xhr.open("POST", "http://csce:8080/test/index.jsp", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=c6c684d9cc99476a7e7e853d77540ceb");
You might want to use the uri encoding global function as a good practice in case you have spaces or other special characters in your parameter:
POST method:
var myVar1 = encodeURIComponent("c6c684d9cc99476a7e7e853d77540ceb");
xhr.open("POST", "http://csce:8080/test/index.jsp", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=" + myVar1);
GET method:
var myVar1 = encodeURIComponent("c6c684d9cc99476a7e7e853d77540ceb");
xhr.open("GET", "http://csce:8080/test/index.jsp?id=" + myVar1, true);
FYI, this is how you retrieve the parameters passed to the JSP page:
We are using JSP's core library (this lib must be in your web app's /WEB-INF/lib/ directory) to output the value of the parameter called "id".
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${param.id}"/>
Rather than pass null in the send method, try passing something like "key=value" which should then show up in your JSP Request object, and you can access it by calling something like:
string myValue = request.getParameter("key");

Categories

Resources