Upload file to an IIS server with AJAX using HTML and JavaScript - javascript

I want to be able to upload an image file (.png, .jpg, etc..) to my web-server (running IIS Server with ASPX) using nothing but HTML and AJAX.
Here's the code:
<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate>
<label for="profile-pic-input">
<img id="profile-pic" name="profilepic" class="profile-pic" src="/Media/user.png" onerror="document.profilepic.src = '/Media/user.png'" />
</label>
<img id="profile-pic-check" onerror="clearImage();" style="display: none;"/>
<input id="profile-pic-input" name="pfpinput" type="file" accept="image/png, image/jpeg"
onchange="readImage(this);" style="display: none" />
<!-- more code that has nothing to do with this question...-->
// JS
function readImage(input) {
document.getElementById("personal-details-error").innerHTML = "";
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#profile-pic').attr('src', e.target.result);
$('#profile-pic-check').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function clearImage() {
document.getElementById("personal-details-error").innerHTML = "Invalid image.";
document.getElementById("profile-pic-input").value = "";
}
$("#personal-details-form").submit(function (e) {
e.preventDefault();
$(".form-field").addClass("used");
document.getElementById("personal-details-error").innerHTML = ""; // Remove errors
if (document.getElementById("personal-details-form").checkValidity()) {
$.ajax({
type: "POST",
url: "../ASPX/verifyChangeDetails.aspx",
data: $("#personal-details-form").serialize(),
success: function (data) {
},
});
}
});
if (Request.Files["pfpinput"] != null) {
HttpPostedFile MyFile = Request.Files["pfpinput"];
Response.Write(MyFile);
} else {
Response.Write("Nope!");
}
I've heard that enctype="multipart/form-data" works, but clearly doesn't in my case...
What should I do in order for my AJAX code to upload the image file?

Turns out I needed a FormData object, and add a file onto it, along with other things, since I was using AJAX.
var formData = new FormData(document.detailsfrm);
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);

Related

how to upload an image with a text post AJAX, php, and html

Hi i am trying to upload an image with comments added to it into a database using php ajax and html.
here is the html part:
<form name="form1" enctype="multipart/form-data" action="">
<h2></h2>
<div class="form-group">
<textarea name="msg" class="form-control status-box" id="post" rows="3" cols="60" placeholder="What\'s on your mind?"></textarea>
<p>Upload an image.</p>
<input type="file" id="postPhoto" name="postPhoto" value="upload" placeholder="Upload Image">
</div>
</form>
<div class="button-group pull-right">
<p class="counter">200</p>
<a href="#" type="submit" onclick="submitChat()" class="post btn btn-primary">
Post</a>
</div><br><br>
this is what i have to the ajax which is on the same page as the html
<script>
function submitChat() {
var file = document.getElementById("postPhoto");
var formData = new FormData();
// alert(formData);
formData.append("file[]", file.files[0]);
if(form1.msg.value == '') {
alert('You must Enter a Post');
return;
}
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById('logs').innerHTML = xmlhttp.responseText;
console.log(xmlhttp.statusText);
}
}
xmlhttp.open('POST', 'userposts.php?msg='+msg, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(formData);
}
<script>
and this is the php part:
$msg = stripslashes(htmlspecialchars($_REQUEST['msg']));
if(isset($_FILES['postPhoto']['type'])) {
$imageData = "";
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES['postPhoto']['name']);
$file_extension = end($temporary);
if((($_FILES['postPhoto']['type'] === 'image/png') || ($_FILES['postPhoto']['type'] == 'image/jpg') || ($_FILES['postPhoto']['type'] == 'image/jpeg')) && ($_FILES['postPhoto']['size'] < 2500000) && in_array($file_extension, $validextensions)) {
if($FILES['postPhoto']['error'] > 0) {
echo "return code: " . $_FILES['postPhoto']['error'] . "<br/><br/>";
}
else {
$imageData = mysqli_real_escape_string($connection, file_get_contents($_FILES["postPhoto"]["tmp_name"]));
}
}
}
$stmt = "INSERT INTO posts VALUES ('', '$uname', '$msg', '$imageData')";
$result = $connection->query($stmt);
the images do not seem to be getting sent to the php file idk how to go about fixing this. any help would be much appreciated.
Maybe Helpful,
You simply can't upload a file with pure Javascript ajax functions (at least not in a cross browser way, see this article for more information)
This is because XMLHttpRequest has no support for multipart/form-data, you can do tricks like using an iframe or use flash.
There are enough articles on the internet that explain this.(maybe helpful)
http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
http://www.faqs.org/rfcs/rfc2388.html
Recomand
Use jQuery Ajax. which have easy lib. support and functions to upload images and submit/parse to destination files.
below sample jQuery AJAX code for demo
$(document).ready(function(){
$(document).on('submit','form[name="form1"]',function(e){
e.preventDefault();
var form = $(this)[0];
var formData = new FormData(form);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});
});
});

How to upload image using javascript, ajax and php

I want to upload an image in onchange of the input type file using AJAX. I can only use javascript, ajax and php.
Look my code:
index.html
<form id="myForm" action="" enctype="multipart/form-data">
<input type="file" name="imagefile" id="imagefile" onchange="uploadImage()">
</form>
upoad.js
function uploadImage(){
try {
ajpass = new XMLHttpRequest();
} catch (e) {
ajpass = new ActiveXObject("Microsoft.XMLHTTP");
}
ajpass.onreadystatechange = epasscheck2;
ajpass.open("post", "http://localhost/moodle/lib/editor/tinymce/plugins/moodleimage/upload.php", true);
ajpass.send();
}
function epasscheck2() {
if ((ajpass.readyState == 4) && (ajpass.status == 200)) {
var restxt = ajpass.responseText;
alert(restxt);
}
}
upload.php
<?php
echo $_FILES["imagefile"]["name"]; //error here
//file upload code here
?>
I am getting the error Undefined index imagefile in upload.php.
I am failed to pass the image file properties(like name, size, tmp_name etc) from upload.js to upload.php.
use the coding below it will help you to validate file
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
<form id="form" action="upload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
you must create a folder "upload".
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "uploaded";
}
}
else
{
echo 'invalid file';
}
}
?>
I feel like a necromancer right now, but regardless, it seems to me that the primary issue in this case was that no actual data was sent in the send() function. Since XMLHttpRequest is being used the form data isn't sent with it as it would be through a redirect directly through HTML. To rectify this, we'd need to first of all grab the file.
const img = document.getElementById("imagefile");
if (img.files.length == 0) return;
const file = img.files[0];
After which I suppose all there is left to do is to actually send the data.
const data = new FormData();
data.append("imagefile", file);
ajpass.send(data);
And with this, you hopefully would get a working result. Since I'm feeling generous, I'll also give you an extra PHP bit that can be useful.
if (isset($_FILES['imagefile']) {
...
}
isset() will more easily help you see if what you're looking for actually exists within the context. It makes finding where things go wrong if they do, and you can avoid nasty error messages.
You can use Dropzone instead of reinventing the wheel,
Here's the link : http://www.dropzonejs.com/#

div used for image display causing difficulties while uploading file;

Here i have a image upload mechanism. It's purpose is to accept an image and display it in a div with id=imageholder . My problem is if i have this image holder div inside my form , it gives upload error (4) . So i get an empty $_FILES array. But if i omit it i get a populated $_FILES array .But i need that div inside the form for design purpose. How i can escape this situation .
with imagehoder div inside form:
without imageholder div :
code may seem long . But none of it is related to the question. It is generally for validating the mime type
full code :
<?php print_r($_FILES);?>
<html>
<body>
<form method='post' enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id='photouploder'>
<div id='imagehoder'></div> // creating problem
<div class="inputWrapper">upload image
<input class="fileInput" id='up' type="file" name="image"/>
</div>
</div>
<input type='submit' value='submit'>
</form>
<script>
var imageholder=document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback,callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
var imgtype= callback(url, header);// headerCallback
callbackTwo(imgtype,blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info=getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype,blob){
var mimearray=['image/png','image/jpeg','image/gif'];
console.log('mimetype is :'+mimetype);
if(mimearray.indexOf(mimetype) !=-1){
printImage(blob);
}else{
document.getElementById('up').value='';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
console.log('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback,getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img=document.createElement('img');
img.setAttribute('src',e.target.result);
img.setAttribute('style','width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "unknown";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return( mimeType(headerString));
}
// Check for FileReader support
function fileread(event){
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray=['image/png','image/jpeg','image/gif'];
var file = event.target.files[0];
if(mimearray.indexOf(file.type)===-1 || file.size >= 2 * 1024 * 1024){
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
console.log("you can't upload this file type");
file=null;
return false;
}else{
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
remoteCallback(file.name, file);
}
}else {
// File and Blob are not supported
console.log('file and blob is not supported');
} /* Drakes, 2015 */
}
document.getElementById('up').addEventListener('change',fileread,false);
</script>
</body>
</html>
First of all: HTML attribute values should always be encapsulated in double quotes.
Second, this is a correct example of reading files using html5 API like you tried:
(Also check the documentation for it: https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
window.onload = function() {
var fileInput = document.getElementById('up');
var fileDisplayArea = document.getElementById('imagehoder');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
<body>
<form method="post" enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id="photouploder">
<div id="imagehoder"></div>
<div class="inputWrapper">upload image
<input class="fileInput" id="up" type="file" name="image" />
</div>
</div>
<input type="submit" value="submit">
</form>
</body>
I'm not sure about the 'design purpose' in your question. If the 'design purpose' means UI design (CSS related), then probably this reason doesn't stand since they are totally irrelevant.
Also, the file upload technology is very mature now. There are bunches of open source implements in all languages and are well-tested and easy-to-use I highly recommend you to take a look at them before implementing it yourself.

How to encode a local image as a multipart/form-data to post to Facebook

I am trying to post a media to Facebook's page managed my me using the FB.api("/{page_id}/photos") from JavaScript sdk. But I am unable to do so successfully.
How do I encode a local image file as a proper multipart/form-data that can be posted to Facebook.
function onChangeMediaReader() {
var file = document.getElementById('post-media').files[0];
reader = new FileReader();
reader.onload = function() {
// displays the selected image in canvas.
document.getElementById('post-media-src').src = reader.result;
document.getElementById('media-container').style.display = "block";
// form-data of the selected image for source param.
formData = new FormData();
formData.append("source", reader.result);
}
if (file) {
reader.readAsDataURL(file);
}
}
function publishPost() {
params.access_token = page_access_token;
params.message = document.getElementById('post-message').innerHTML;
if (formData) {
params.source = formData;
}
FB.getLoginStatus(function(response) {
FB.api(
'/' + page_id + '/photos',
"POST",
params,
function(response) {
console.log(response);
});
});
}
<form id="image-data" method="post" enctype="multipart/form-data">
<input type="file" name="source" id="post-media" accept="image/*" onchange="onChangeMediaReader();" />
<label for="post-media">Upload media</label>
<br />
<br />
</form>
<button id="publish-post" onclick="publishPost();">Submit</button>
Response message
"(#324) Requires upload file",
"type: "OAuthException"

Upload image using javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});

Categories

Resources