2014-01-05 3 views
0

Я новичок в android, и я пытаюсь загрузить звуковой файл, выбранный из мобильного, и загрузить его на сервер. Я нашел учебник в Интернете, и это то, что я сделал. Вот мой андроид код:Загрузка аудиофайла на сервере с 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 он говорит файл, написанный, а затем отобразить его, что было ошибка при загрузке файла.

Это мой 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/ 
+0

рассмотреть вопрос о включении Logcat ошибка также – Nizam

+0

выполнить 'doFileUpload()' в отдельном потоке, а не в основной нить. – Nizam

+0

Извините, но как это сделать? @Nizam – user3089900

ответ

0
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); 
    } 
+0

Можете ли вы изменить его в соответствии с моим сенарио? – user3089900

+0

нет этот один не сработал @nizam – user3089900

+0

эта линия правильная? dos.writeBytes («Content-Disposition: form-data; name = \» uploadedfile \ "; filename = \" "+ selectedPath +" "+ lineEnd); – user3089900

Смежные вопросы