Android upload file with PHP program on the server Accept (a)

Source: Internet
Author: User
Tags php server

PHP Server accepts programs: file_up.php.

<?PHP/*require_once (' lib/session_config.php ');    Require_once (' lib/flydc.php ');    Require_once (' lib/common.php '); Require_once (' config.php '); */    //header ("Content-type:text/html;charset=utf-8"); Var_dump ($_server[' http_range ');    $fileUp=NewFileup (); $fileUp-UploadFile (); Exit; classFileup { Public $isHaveFid=false;  Public $target _path= ".. /files/";//path to file access                 Public $uid,$fid,$ext,$alllength,$poss,$finish; functionInitData () {$this->fid =$_get[' FID ']; $this->ext =$_get[' ext ']; $this->poss =$_get[' POS ']; }                functionUploadFile () {$this-InitData (); $absoluteName= "";//$this->getdir (). " /". BaseName ($_files[' uploadedfile ' [' name ']);                        $handleRead=NULL; $fid= ""; $handleWrite=NULL; if(!Empty($_files[' UploadedFile '] [' Tmp_name ']))            {                $handleRead=fopen($_files[' UploadedFile '] [' Tmp_name '], ' RB '); //$extend = pathinfo ($_files[$name [' name ']); $extend [' extension '] extension                                if(!Empty($this-&GT;FID))//FID exists is then last uploaded                    $fid=$this-FID; Else //FID does not exist, as the first upload, generates a FID                    $fid= Time().‘ _‘.Mt_rand(1,22222). ".".$this-ext; $absoluteName=$this->getdir (). " /".$fid; $handleWrite=fopen($absoluteName, ' a '); $buffer= ' ';  while(!feof($handleRead))                  {                    $buffer=fread($handleRead, 1024*128); if(strlen($buffer) <=0)                         Break; fwrite($handleWrite,$buffer); }                                fclose($handleWrite); fclose($handleRead); Echo $fid;//return FID to the server                $this->savelog ("$fidUpload successful "); }Else            {                Echo"Fail"; $this->savelog ("Upload failed"); }        }                                functionSavelog ($content)        {            $logpath=$this->getdir (). " /".Date("Y-m-d", Time())." _log.txt "; $result=fopen($logpath, ' a '); fwrite($result,Date("Y-m-d h:i:s", Time())." ========== ".$content." \ r \ n "); fclose($result); }                functionGetdir () {$day _dir=$this->target_path.Date("Ymd", Time()); if(!Is_dir($day _dir))            {                mkdir($day _dir, 0777,true); }            return $day _dir; }                    }         ?>

Androiud Client Java code

 Public voiddoupload () {//the file to uploadString pathstring = filemanager.getparentdirectory () + "Media/video_3_20141222145045024.mp4";//Video_3_20141222145045024.mp4 Video_3_20141224153340976.mp4//Address to uploadString Accepturl = "http://10.0.10.3/flyguard/mobileapi/file_up.php?fid=" + This. fidstring+ "&pos=&ext=mp4"; Randomaccessfile RAF=NULL; Try{RAF=NewRandomaccessfile (pathstring, "R"); LongAlllength=raf.length (); Raf.seek (0); byte[] buffer =New byte[128*1024];//128k            intCount = 0;  while((count = raf.read (buffer))! =-1)            {//count = raf.read (buffer);String result =Uploadfil (Accepturl,buffer); System.out.println ("Mediaactivity doupload return:" +result+ "Count:" +count);  Break; }                               } Catch(Exception e) {e.printstacktrace (); }finally{                            Try                {                    if(raf!=NULL) Raf.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }                    } PublicString Uploadfil (String Accepturl,byte[] data) {String End= "\ r \ n"; String Twohyphens= "--"; String Boundary= "******"; Try{URL URL=NewURL (Accepturl); HttpURLConnection HttpURLConnection=(HttpURLConnection) url.openconnection (); //set the stream size for each transfer to effectively prevent the phone from crashing due to low memory//This method is used to enable a stream that does not have an internally buffered HTTP request body when the content length is not known beforehand. Httpurlconnection.setchunkedstreamingmode (data.length);//128*1024 is 128k//allow input/output streamHttpurlconnection.setdoinput (true); Httpurlconnection.setdooutput (true); Httpurlconnection.setusecaches (false); //using the Post methodHttpurlconnection.setrequestmethod ("POST"); Httpurlconnection.setrequestproperty ("Connection", "keep-alive"); Httpurlconnection.setrequestproperty ("Charset", "UTF-8"); Httpurlconnection.setrequestproperty ("Content-type", "multipart/form-data;boundary=" +boundary);//Application/octet-stream Multipart/form-dataDataOutputStream dos =NewDataOutputStream (Httpurlconnection.getoutputstream ()); Dos.writebytes (Twohyphens+ Boundary +end); Dos.writebytes ("Content-disposition:form-data; Name=\ "Uploadedfile\"; Filename=\ ""//+pathstring.substring (Pathstring.lastindexof ("/") +1)+ "myFileName" + "\" "+end);                                    Dos.writebytes (end); Dos.write (data,0, data.length);            Dos.writebytes (end); Dos.writebytes (Twohyphens+ Boundary + Twohyphens +end);                                    Dos.flush (); String reponse= ""; if(Httpurlconnection.getresponsecode () = = 200) {InputStream is=Httpurlconnection.getinputstream (); InputStreamReader ISR=NewInputStreamReader (IS, "Utf-8"); BufferedReader BR=NewBufferedReader (ISR);  while(NULL!=Br.readline ()) {reponse+=Br.readline ();            } is.close (); } System.out.println ("Mediaactivity Uploadfil reponse:" +reponse);            Dos.close (); returnreponse; } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); System.out.println ("Mediaactivity uploadfil Exception:" +e.getmessage ()); }                return""; }

Android upload file with PHP program on the server Accept (a)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.