php-Android文件上传-$_FILES返回空

php-Android文件上传-$_FILES返回空,第1张

概述我正在尝试使用Android脚本将图像从AndroidApp上传到服务器.HTTP响应返回状态为OK:200,但是$_FILES[“upfile”][“name”]返回空.我已经检查了我的文件夹权限,Aready是777.我的.java类/********************UPLOADDATA*************************************/classUp

我正在尝试使用Android脚本将图像从Android App上传到服务器.
http响应返回状态为OK:200,但是$_fileS [“ upfile”] [“ name”]返回空.
我已经检查了我的文件夹权限,Aready是777.

我的.java类

  /********************UPLOAD DATA*************************************/class Uploadimg extends AsyncTask<VoID, VoID, VoID>{    NetworkInfo net;    Messaging uActivity;    httpURLConnection connection = null;    DataOutputStream outputStream = null;    DatainputStream inputStream = null;    String folderPath;    String arrayOffiles[];    file root;    file allfiles;    String urlServer = "http://bmcpublicIDade.com.br/chat/upload.PHP";    String lineEnd = "\r\n";    String twoHyphens = "--";    String boundary =  "*****";    int bytesRead, bytesAvailable, bufferSize;    byte[] buffer;    int maxBufferSize = 10*1024*1024;    URL url;     ProgressDialog pDialog = new ProgressDialog(Messaging.this);    @OverrIDe    protected voID onPreExecute() {        Log.d(" Uploadimg","onPreRequest");            pDialog.setMessage("Uploading GPS Data. Please wait...");            pDialog.setIndeterminate(false);            pDialog.setCancelable(true);            pDialog.show();    }    @OverrIDe    protected VoID doInBackground(VoID... params) {         Log.d(" UploadData","doInBackground");         String filename = ""+selectedpath;         httpURLConnection conn = null;         DataOutputStream dos = null;         BufferedReader inStream = null;         String lineEnd = "rn";         String twoHyphens = "--";         String boundary =  "*****";         int bytesRead, bytesAvailable, bufferSize;         byte[] buffer;         int maxBufferSize = 10*1024*1024;         String responseFromServer = "";         String urlString = "http://bmcpublicIDade.com.br/chat/upload.PHP";         try         {          //------------------ CLIENT REQUEST         fileinputStream fileinputStream = new fileinputStream(new file(selectedpath) );          // open a URL connection to the Servlet          URL url = new URL(urlString);          // Open a http connection to the URL          conn = (httpURLConnection) url.openConnection();          // Allow inputs          conn.setDoinput(true);          // Allow Outputs          conn.setDoOutput(true);          // Don't use a cached copy.          conn.setUseCaches(false);          // Use a post method.          conn.setRequestMethod("POST");          conn.setRequestProperty("Connection", "Keep-Alive");          conn.setRequestProperty("enctype", "multipart/form-data");          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);          conn.setRequestProperty("upfile", filename);           dos = new DataOutputStream( conn.getoutputStream() );          dos.writeBytes(twoHyphens + boundary + lineEnd);          dos.writeBytes("Content-disposition: form-data; name=\"upfile\"; filename='"+ selectedpath +"'" + lineEnd);          dos.writeBytes(lineEnd);          // create a buffer of maximum size          bytesAvailable = fileinputStream.available();          bufferSize = Math.min(bytesAvailable, maxBufferSize);          buffer = new byte[bufferSize];          // read file and write it into form...          bytesRead = fileinputStream.read(buffer, 0, bufferSize);          while (bytesRead > 0)          {           dos.write(buffer, 0, bufferSize);           bytesAvailable = fileinputStream.available();           bufferSize = Math.min(bytesAvailable, maxBufferSize);           bytesRead = fileinputStream.read(buffer, 0, bufferSize);          }          // send multipart form data necesssary after file data...          dos.writeBytes(lineEnd);          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);       // Responses from the server (code and message)          serverResponseCode = conn.getResponseCode();          String serverResponseMessage = conn.getResponseMessage();          Log.i("upfile", "http Response is : "                  + serverResponseMessage + ": " + serverResponseCode);          if(serverResponseCode == 200){              runOnUiThread(new Runnable() {                   public voID run() {                       String msg = "file Upload Completed.\n\n See uploaded file here : \n\n"                                     +" http://**********/media/uploads/";                       messageText.setText(msg);                       Toast.makeText(Messaging.this, "file Upload Complete.",                                     Toast.LENGTH_SHORT).show();                   }               });                          }              // close streams          Log.e("DeBUG","gravando arquivo: " + filename);          fileinputStream.close();          dos.flush();          dos.close();         }         catch (MalformedURLException ex)         {              Log.e("DeBUG", "erro: " + ex.getMessage(), ex);         }         catch (IOException ioe)         {              Log.e("DeBUG", "erro: " + ioe.getMessage(), ioe);         }         //------------------ read the SERVER RESPONSE         try {               inStream = new BufferedReader ( new inputStreamReader(conn.getinputStream()) );               String str;               while (( str = inStream.readline()) != null)               {                    Log.e("DeBUG","ServIDor diz:  "+str);               }               inStream.close();         }         catch (IOException ioex){              Log.e("DeBUG", "erro: " + ioex.getMessage(), ioex);         }    return null;    }    @OverrIDe    protected voID onPostExecute(VoID result) {         Log.d(" UploadMSG","onPost");        pDialog.dismiss();        messageText.setText("Uploaded");    }}/********************END OF UPLOAD*************************************/

这是我的PHP文件

// Where the file is going to be placed$target_path = "uploads/";/* Add the original filename to our target path.Result is "/uploads/filename.extension" */$target_path = $target_path . basename( $_fileS['upfile']['name']);if( $_fileS['upfile'] ){    if(move_uploaded_file($_fileS['upfile']['tmp_name'], $target_path)) {        // $qry = "UPDATE users set image=".$target_path." where username='$username'";        // $db->query($qry);        echo "O arquivo ".  basename( $_fileS['upfile']['name']).        " está sendo enviado";    } else{        echo "Ocorreu um erro ao realizar envio de arquivo, por favor tente novamente!\n";        echo "Nome do arquivo: " .  basename( $_fileS['upfile']['name'])."\n";        echo "target_path: " .$target_path;    }}else{    echo "Nenhum arquivo careregado!";     /*** ever enters here!!! ***/}

你能帮助我吗?

谢谢 !!!

解决方法:

我刚刚遇到了同样的问题.发布文件成功,响应为200,但是_fileS为空.我通过指定Content-Length标头解决了该问题.例如.:

conn.setRequestProperty("Content-Length", Integer.toString(fileinputStream.available()));

编辑:因此,使用此文件时,该文件出现在_fileS中,但错误代码为3.但是,我也调用了conn.setChunkedStreamingMode(1024);.删除Content-Length和对setChunkedStreamingMode的调用对我来说是可行的,但是我很确定空的_fileS与Content-Length字段设置不正确有关.

总结

以上是内存溢出为你收集整理的php-Android文件上传-$_FILES返回空全部内容,希望文章能够帮你解决php-Android文件上传-$_FILES返回空所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1092918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存