0

I am trying to upload an image in html page using the <input type="file"> element. I want to use the uploaded image to replace another image on the page. However, the control does not pass onto the java script function. Am trying to find out why the control does not pass. Below is the code I am using:

<label>Upload a Picture</label
<img src="unknown_person.jpg" height="250" width="250"></img>

<div>
   <form name="image1"  enctype="multipart/form-data" action="/" method="POST" onsubmit="return UploadPic()">
      <input type="file" name="imgfile"></input>
   </form>
</div>

Thanks in advance.

1
  • To add to the above question, am trying to upload an image and then call javascript function that replaces the image of existing <img> Commented Jul 10, 2013 at 5:15

2 Answers 2

1

You can't intercept a file upload in Java Script. The file has to be uploaded to the server, and then the page has to be rerendered

Sign up to request clarification or add additional context in comments.

4 Comments

But can't I call some function direclty after file is uploaded? Right now it doesn't seem to call the function UploadPic(). Any suggestions on that?
Where are you submitting the form? It won't call UploadPic until the form is actually submitted. Selecting a file simply sets a value in a form field.
@mike-christensen, could you give an example of what you mean by submitting the form? Do you mean I should provide some path in action attribute where form is posted and then comes back to js function?
@BuzzLightYear - I mean you need a <input type="submit" /> button somewhere. Once clicked, the form's onsubmit event will be fired and the selected file will be uploaded to the server.
0

One approach would be using AJAX to query the backend on where the image was uploaded. Like so

var pullImage = function()
{
  // do ajax work
  return image ? propagateHTML('element', image.uri) : fallback();
}

var propagateHTML = function(id, uri)
{
  document.getElementById(id).innerHTML = uri;
}

1 Comment

My problem is call not going to the javascript function "UploadPic()". so, am not able to use the code inside that. So, the code you gave will have same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.