[英]mp3 upload php from android
我正在嘗試將mp3文件從我的Android手機上傳到php服務器。 我使用以下代碼將其編碼為字符串,然后使用httpPost上傳(為此,我沒有在本文中包含代碼以保持其重點)。
File audioStorageDir = new File(Environment.getExternalStorageDirectory().getPath(), "LEADVoices");
InputStream is;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
System.out.println("The name of the audio file " + audioName);
is = new FileInputStream(audioStorageDir.getAbsolutePath() + File.separator + audioName);
int bytesAvailable = is.available();
int maxBufferSize = 1000;
byte[] buffer = new byte[bytesAvailable];
int bytesRead = is.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
baos.write(buffer, 0, bytesAvailable);
bytesAvailable = is.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bytesAvailable);
}
System.out.println("Uploaded an audio file");
byte[] bytes = baos.toByteArray();
String encodedAudio = Base64.encodeToString(bytes, Base64.DEFAULT);
choiceList.add(new BasicNameValuePair("audio",encodedAudio));
is.close();
baos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("bytearrayoutputstream error1");
} catch (IOException e) {
e.printStackTrace();
System.out.println("bytearrayoutputstream error2");
}
在服務器端,我正在使用以下代碼對字符串進行解碼。 但是,無法播放在服務器端生成的mp3文件。 任何人都知道哪里錯了嗎?
$audio = 'myfile.mp3';
$encodedString = $_POST['audio'];
$dir = '../myfolder/Audios';
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$decoded=base64_decode($encodedString);
$filepath = $dir.'/'.$audio;
file_put_contents($filepath,$decoded);
}
我不建議使用base64編碼文件,因為這是一項非常繁重的任務,請使用多部分形式,這是一個示例
new Upload().execute(selectedPath); //path to file like /mnt/sdcard/file_name
這是Asynctask
private class Upload extends AsyncTask<String, String, String>{
protected void onPreExecute() {
Toast.makeText(activity, "Start upload...", Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = params[0];
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "your php upload page here";
try{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// 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=\"" + file_name + "\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
//Other parameter like key=value&key1=value but you can also use list or another method
String[] posts = post.split("&");
int max = posts.length;
for(int i=0; i<max;i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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;
String response_data = "";
while (( str = inStream.readLine()) != null){
response_data = response_data+str;
}
inStream.close();
return response_data;
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return "";
}
protected void onPostExecute(String result){
Log.i("result", result);
if(result.equals("ok")){
Toast.makeText(activity, "Upload succesfull", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(activity, "Error on upload", Toast.LENGTH_LONG).show();
}
}
}
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.