【问题标题】:Uploading audio file on server from android从android上传服务器上的音频文件
【发布时间】:2014-01-05 17:16:57
【问题描述】:

我是 android 新手,我正在尝试上传从手机中选择的声音文件并将其上传到服务器。我在互联网上找到了教程,这就是我所做的。这是我的安卓代码:

public class MainActivity extends Activity {

 private static final int SELECT_AUDIO = 2;
public static String selectedPath = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      openGalleryAudio();
}

public void openGalleryAudio(){

Intent intent = new Intent();
    intent.setType("audio/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
  }

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        if (requestCode == SELECT_AUDIO)
        {
            System.out.println("SELECT_AUDIO");
            Uri selectedImageUri = data.getData();
            selectedPath = getPath(selectedImageUri);
            System.out.println("SELECT_AUDIO Path : " + selectedPath);
            new SaveImageTask().execute(selectedPath);
            }

    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

private void doFileUpload(){
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "rn";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String responseFromServer = "";
    Log.d("function", "this is the value of selected path"+selectedPath);
    String urlString = "http://10.0.2.2/Upload_App/WebService/upload_audio.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("Content-Type", "multipart/form-data;boundary="+boundary);
     dos = new DataOutputStream( conn.getOutputStream() );
     dos.writeBytes(twoHyphens + boundary + lineEnd);
     dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "" + lineEnd);

     //dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";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);
     // close streams
     Log.e("Debug","File is written");
     fileInputStream.close();
     dos.flush();
     dos.close();
    }
    catch (MalformedURLException ex)
    {
         Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
         Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    //------------------ read the SERVER RESPONSE
    try {
          inStream = new DataInputStream ( conn.getInputStream() );
          String str;

          while (( str = inStream.readLine()) != null)
          {
               Log.e("Debug","Server Response "+str);
          }
          inStream.close();

    }
    catch (IOException ioex){
         Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
  }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public class SaveImageTask extends AsyncTask<String, String, String>
{
    @Override
    protected String doInBackground(String... urls) {
        // TODO Auto-generated method stub
        doFileUpload();
        return null;
    }
    protected void onPostExecute(Long result) {
        Log.d("File Uploading", "File is uploaded");
     }

}

}

这是我在服务器端的 PHP 代码

$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}

但在我的 logcat 中,它说文件已写入,然后显示上传文件时出错。

这也是我的日志猫

   01-05 14:11:06.475: I/System.out(668): SELECT_AUDIO
   01-05 14:11:06.695: I/System.out(668): SELECT_AUDIO Path : /mnt/sdcard/splash.mp3
   01-05 14:11:06.835: D/function(668): this is the value of selected   path/mnt/sdcard/splash.mp3
   01-05 14:11:07.535: D/dalvikvm(668): GC_FOR_MALLOC freed 4192 objects / 269392 bytes in 144ms
   01-05 14:11:07.545: E/Debug(668): File is written
   01-05 14:11:08.245: E/Debug(668): Server Response <br />
   01-05 14:11:08.315: E/Debug(668): Server Response <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
   01-05 14:11:08.485: E/Debug(668): Server Response <tr><th align='left'  bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: uploadedfile in     C:\wamp\www\Upload_App\WebService\upload_audio.php on line <i>6</i></th></tr>
  01-05 14:11:08.525: E/Debug(668): Server Response <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
  01-05 14:11:08.665: E/Debug(668): Server Response <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
  01-05 14:11:08.775: E/Debug(668): Server Response <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0206</td><td bgcolor='#eeeeec' align='right'>368744</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\Upload_App\WebService\upload_audio.php' bgcolor='#eeeeec'>..\upload_audio.php<b>:</b>0</td></tr>
  01-05 14:11:08.775: E/Debug(668): Server Response </table></font>
  01-05 14:11:08.805: E/Debug(668): Server Response <br />
  01-05 14:11:08.855: E/Debug(668): Server Response <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
  01-05 14:11:08.935: E/Debug(668): Server Response <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: uploadedfile in C:\wamp\www\Upload_App\WebService\upload_audio.php on line <i>7</i></th></tr>
  01-05 14:11:08.965: E/Debug(668): Server Response <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
  01-05 14:11:09.045: E/Debug(668): Server Response <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
  01-05 14:11:09.125: E/Debug(668): Server Response <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0206</td><td bgcolor='#eeeeec' align='right'>368744</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\Upload_App\WebService\upload_audio.php' bgcolor='#eeeeec'>..\upload_audio.php<b>:</b>0</td></tr>
  01-05 14:11:09.125: E/Debug(668): Server Response </table></font>
  01-05 14:11:09.145: E/Debug(668): Server Response <br />
  01-05 14:11:09.175: E/Debug(668): Server Response <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
  01-05 14:11:09.265: E/Debug(668): Server Response <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: uploadedfile in C:\wamp\www\Upload_App\WebService\upload_audio.php on line <i>8</i></th></tr>
  01-05 14:11:09.295: E/Debug(668): Server Response <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
  01-05 14:11:09.355: E/Debug(668): Server Response <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
  01-05 14:11:09.425: E/Debug(668): Server Response <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0206</td><td bgcolor='#eeeeec' align='right'>368744</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\Upload_App\WebService\upload_audio.php' bgcolor='#eeeeec'>..\upload_audio.php<b>:</b>0</td></tr>
  01-05 14:11:09.425: E/Debug(668): Server Response </table></font>
  01-05 14:11:09.445: E/Debug(668): Server Response <br />
  01-05 14:11:09.475: E/Debug(668): Server Response <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
  01-05 14:11:09.545: E/Debug(668): Server Response <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: uploadedfile in C:\wamp\www\Upload_App\WebService\upload_audio.php on line <i>9</i></th></tr>
  01-05 14:11:09.565: E/Debug(668): Server Response <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
  01-05 14:11:09.625: E/Debug(668): Server Response <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
  01-05 14:11:09.695: E/Debug(668): Server Response <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0206</td><td bgcolor='#eeeeec' align='right'>368744</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\Upload_App\WebService\upload_audio.php' bgcolor='#eeeeec'>..\upload_audio.php<b>:</b>0</td></tr>
  01-05 14:11:09.695: E/Debug(668): Server Response </table></font>
  01-05 14:11:09.725: E/Debug(668): Server Response There was an error uploading the file, please try again!<br />
  01-05 14:11:09.745: E/Debug(668): Server Response <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
  01-05 14:11:09.795: E/Debug(668): Server Response <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: uploadedfile in C:\wamp\www\Upload_App\WebService\upload_audio.php on line <i>14</i></th></tr>
   01-05 14:11:09.815: E/Debug(668): Server Response <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
   01-05 14:11:09.875: E/Debug(668): Server Response <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
   01-05 14:11:09.935: E/Debug(668): Server Response <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0206</td><td bgcolor='#eeeeec'  align='right'>368744</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\Upload_App\WebService\upload_audio.php' bgcolor='#eeeeec'>..\upload_audio.php<b>:</b>0</td></tr>
 01-05 14:11:09.935: E/Debug(668): Server Response </table></font>
 01-05 14:11:09.955: E/Debug(668): Server Response filename: target_path: uploads/  

【问题讨论】:

  • 考虑包括 Logcat 错误
  • 在单独的线程中执行doFileUpload(),而不是在主线程中。
  • 对不起,怎么办? @尼扎姆
  • 很好用AsyncTask
  • @Nizam 你能帮我写一个演示吗?

标签: php android


【解决方案1】:
private class UploadAudioTask extends AsyncTask<Uri , Integer, Long> {

     protected Void doInBackground(Uri selectedPath) {
          doFileUpload(selectedPath);//I have added this param as I saw, you are using this value in your function, you can add or remove it according to your usability.
     }

     protected void onPostExecute(Void result) {
         showDialog("Uploaded");
     }
 }

把它称为 --

    if (requestCode == SELECT_AUDIO)
    {
        System.out.println("SELECT_AUDIO");
        Uri selectedImageUri = data.getData();
        selectedPath = getPath(selectedImageUri);
        System.out.println("SELECT_AUDIO Path : " + selectedPath);
        new UploadAudioTask ().execute(selectedPath);
    }

【讨论】:

  • 可以根据我的情况修改吗?
  • 这条线是否正确? dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "" + lineEnd);
  • 受保护的长 doInBackground(Uri selectedPath) { doFileUpload(selectedPath); } 这个给出错误
  • @user3089900 没用是什么意思?您必须编辑问题并从 logcat 中指定错误。
  • 注意:未定义索引:第 6 行 C:\wamp\www\Upload_App\WebService\upload_audio.php 中的上传文件
猜你喜欢
  • 1970-01-01
  • 2018-12-20
  • 2023-04-09
  • 2018-06-07
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多