inline jquery / js to an external file.

Hi all !

Back with yet another small (I hope) issue. Below is a working jquery snippet which shows a preview of an image once the image is selected. It is however causing a CSP conflict because of the “this” parameter used in onchange="readURL(this)". Please can someone explain how to get this working by making the jquery external to the file and not using the “this” keyword.

HTML

Select the file to upload: 	<input type="file" name="userfile" onchange="readURL(this)" /><br>
			        <img id="image" src="#" alt="load_image" />
				<input type="submit" name="upload" value="upload">
	</form>

JS

		<script>
		function readURL(input){
			if (input.files && input.files[0]) 
			{
				var reader = new FileReader();
				reader.onload = function (e) {
				  $('#image')
					.attr('src', e.target.result)
					.width(200)
					.height(200);
				};
				reader.readAsDataURL(input.files[0]);
			}else{
				alert( "File not selected or browser incompatible." );
			}
		alert("Error");	
		}
	</script>

Any help appreciated.
Thanks all.

Just remove the this. It’s not being used.

Hi senocular ! Thanks for the response. Sorry there was a small mistake I made in my code. I forgot to pass give an argument to the function. I have made the change. this is passed to the readURL function as input.Kindly have another look.

Thanks.

Hi ! I managed to do it myself. Find below the code for the same. If there is any issue with it please let me know. Else for someone else like me I post the code below:

<html>
<head>
	<title>1. File Upload To Database</title>
	<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
	<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
	<meta charset=utf-8 />

</head>
<body>	
	<form action="#" method="POST" ENCTYPE="multipart/form-data">

		Select the file to upload: 	<input type="file" id="file" name="userfile" /><br> <!-- onchange="readURL()" /><br> -->
									<img id="image" src="#" alt="load_image" /><br>
									<input type="submit" name="upload" value="upload">
	</form>
	
	<script>
		$(window).load(function(){ 
			$('#file').change(function(){
			var files = !!this.files ? this.files : []; 
				if (files && files[0]) 
				{
					var reader = new FileReader();
					reader.onload = function (e) {
					  $('#image')
						.attr('src', e.target.result)
						.width(200)
						.height(200);
					};
					reader.readAsDataURL(files[0]);
				}else{
					alert( "File not selected or browser incompatible." );
				}
			});
		});	
	</script>

The onchange = “readURL()” has to be removed. An id=“file” had to be added.
Thanks all

1 Like