简体   繁体   中英

How to upload a file and display its information

I want to build a web service that will process some files.

Here is what I want to do:

  1. User uploads a file to the server using "upload form", the file is saved as a temporary file on the server-side
  2. Server-side python script processes the temporary file and produces some statistics (for example, number of lines and words in the file)
  3. The statistics are displayed near the "upload form"

The question here is: I would like the file to be processed in the background just after it is uploaded, and after it is done, .append() the produced results to the current view. I do not want to assign a script to <form action="processing_script.php">... because the user will be redirected to the processing_script.php after clicking the Upload button.

Any clues? Maybe some neat ajax call?

 function ajaxRequest(){
  var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
  if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
   for (var i=0; i<activexmodes.length; i++){
    try{
     return new ActiveXObject(activexmodes[i])
    }
    catch(e){
     //suppress error
    }
   }
  }
  else if (window.XMLHttpRequest) // if Mozilla, Safari etc
   return new XMLHttpRequest()
  else
   return false
 }

 function postFile(){
 var mypostrequest=new ajaxRequest()
 mypostrequest.onreadystatechange=function(){
  if (mypostrequest.readyState==4){
   if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
    document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
   }
   else{
    alert("An error has occured making the request")
   }
  }
 }
 var file = document.getElementById("my_file");
 var parameters="file="+file //i am not sure of this peice though
 mypostrequest.open("POST", "basicform.php", true)
 mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
 mypostrequest.send(parameters)
 }

Yeah, you'll need ajax for that. Create the form as usual, then submit it using Ajax. Form handling can be done as usual.

If you google 'file upload Ajax' I'm sure you can find everything you need :)

yeah, i'd made second ajax request and run it with schedule (eg every 10 seconds). it will query the server if uploaded file is processed. the server may even do the file processing in external program. the php-script that accepts second ajax request checks some READY status and give client the answer YES/NO/FAILED. when client accepts YES answer it refirects user to the RESULTS PAGE. if it accepts NO, it alerts user the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM