在android上传文本文件时出错(服务器无法理解浏览器发送的请求)

时间:2013-11-13 06:41:34

标签: android

”                尝试         {             String upurl =;             String path = getFilesDir()。getPath();             String filename = dq.fetchfilename();             filename = filename.replaceFirst(“M”,“T”);             path = path.concat(“/”+ filename);

        File file = new File(path);

           HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(upurl);

InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
            reqEntity.setContentType("binary/octet-stream");
            reqEntity.setChunked(true); // Send in multiple parts if needed
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
 String str= inputStreamToString(response.getEntity().getContent()).toString();
            //Do something with response...
            if(str.equalsIgnoreCase("false"))
            {
                bf=false;
            }

    }
    catch (Exception e) {
        // TODO: handle exception
        bf=false;
        e.printStackTrace();
    }
    return null;

    }
 '
//error while uploading a text file onto the server 
//bad request server could not understand the request sent by your browser

1 个答案:

答案 0 :(得分:0)

Android代码 -

public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
  URL connectURL;
  String params;
  String responseString;
  String fileName;
  byte[] dataToServer;
  FileInputStream fileInputStream;
  private int serverResponseCode;

  private String serverResponseMessage;

  private static final String TAG = "Uploader";


  public void setUrlAndFile(String urlString, File fileName)
  {
     Log.d(TAG,"StartUploader");

  try
  {
    fileInputStream = new FileInputStream(fileName);
    connectURL = new URL(urlString);
  }
  catch(Exception e)
  {
    e.getStackTrace();
    publishProgress(e.toString());

  }
  this.fileName = fileName.getAbsolutePath()+".txt";

}

synchronized void doUpload()
{
  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  Log.d(TAG,"lv1");

 try
{
    Log.d(TAG,"doUpload");
    publishProgress("Uploading...");

    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection","Keep-Alive");
    conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
    DataOutputStream dos  = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
    dos.writeBytes(lineEnd);

    Log.d(TAG,"LvA");
    Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);

    int bytesAvailable = fileInputStream.available();

    int maxBufferSize = 1024;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);

    byte[] buffer = new byte[bufferSize];

    int bytesRead = fileInputStream.read(buffer,0, bufferSize);
    Log.d(TAG,"LvB");
    while(bytesRead > 0)
    {

        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    fileInputStream.close();
   dos.flush();

    InputStream is = conn.getInputStream();
    int ch;
    Log.d(TAG,"LvC");
    StringBuffer buff = new StringBuffer();
    while((ch=is.read()) != -1)
    {
        buff.append((char)ch);
    }
   // publishProgress(buff.toString());
    dos.close();


 // Responses from the server (code and message)
    serverResponseCode = conn.getResponseCode();
    serverResponseMessage = conn.getResponseMessage();
   // Log.d(TAG,"Buffer "+buff.toString());

    Log.d(TAG,"Server Response "+serverResponseMessage);
}

  catch(Exception e)
  {
    e.getStackTrace();
     publishProgress(e.toString());
  }
}

 @Override
 protected Object doInBackground(Object... arg0) 
 {
   Log.d(TAG,"lv1a");
   doUpload();
   Log.d(TAG,"Uploading Completed! Path: "+connectURL);

   return null;
  }

 protected void onProgressUpdate(String... progress)
 {
  //this.info.setText(progress[0]);
    Log.d("Progress", progress[0]);
  }


}

PHP代码 -

< ?php

  $file_path = "uploads/";

  $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
  if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
     echo "success";
  } else{
     echo "fail";
  }
  ? >

您也可以查看link 1 link 2