У меня возникла проблема при загрузке файла MP3 на сервер с помощью Android + Php. Я использую Android Studio. Все работает идеально, только когда загрузка завершена, я не могу найти свой файл на стороне сервера.
мой код Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.uploadfile.milad.MainActivity">
<Button
android:id="@+id/upload"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload"
tools:layout_editor_absoluteX="144dp"
tools:layout_editor_absoluteY="216dp" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/upload"
android:layout_margin="15dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp" />
мой код активности:
package com.uploadfile.milad;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions();
Log.w("LOG", Environment.getDataDirectory().toString());
Button upload = (Button) findViewById(R.id.upload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 0);
/*final String path = "/storage/emulated/0/Download/pdf.pdf";
upload(path);*/
}
});
}
public void upload(String path){
Upload upload = new Upload(MainActivity.this, path);
progressBar.setProgress(0);
progressBar.setMax(100);
Log.w("LOG","file exist: " + upload.fileExist());
upload.run(new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.w("LOG","response: " + responseBody.toString() + " status code: " + statusCode);
if(statusCode == 200){ //responseBody.toString().equals("success")) {
Toast.makeText(MainActivity.this, "Upload Suecced",Toast.LENGTH_LONG).show();
progressBar.setProgress(progressBar.getMax());
}
else {
Toast.makeText(MainActivity.this, "Upload Failed",Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "Upload Failed: " + error.getMessage(),Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
double percentage = (double)bytesWritten/(double)totalSize * 100;
progressBar.setProgress ((int)percentage);
Log.w("LOG","Percentage: " + percentage);
super.onProgress(bytesWritten, totalSize);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && data != null) {
if(resultCode == RESULT_OK) {
final String path = data.getData().getPath().replace(":","/").replace("document","storage");
Log.w("LOG","FILE PATH: " + path);
upload(path);
}
}
}
public void checkPermissions(){
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
}
мой класс загрузки:
package com.uploadfile.milad;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.location.Address;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import java.io.File;
import java.io.FileNotFoundException;
import cz.msebera.android.httpclient.client.ResponseHandler;
public class Upload {
private static String URL = "http://10.0.2.2:8000/edsa-proj/test%20lab/up/upload.php", KEY = "uploaded_file";
private String fileAddress;
private File file;
private AsyncHttpClient httpClient;
private Context context;
private RequestParams params;
public Upload(Context context, String FileAddress){
this.fileAddress = FileAddress;
this.context = context;
httpClient = new AsyncHttpClient();
params = new RequestParams();
file = new File(FileAddress);
}
public boolean fileExist(){
if(file.exists())
return true;
else
return false;
}
/*returns
true if file is exist
false if file not exist
* */
public boolean run(ResponseHandlerInterface handler){
if(putFileParam(file)) {
httpClient.post(context, URL, params, handler);
return true;
}
else {
return false;
}
}
/*returns
true if file is exist
false if file not exist
* */
private boolean putFileParam(File file)
{
try {
params.put(KEY, file);
return true;
}
catch(Exception e) {
Log.w("LOG_UPLOAD", e.toString());
return false;
}
}
}
и код php:
<?php
$file_path = "uploads/";
$KEY = 'uploaded_file';
$file_path = $file_path . basename( $_FILES[$KEY]['name']);
if(move_uploaded_file($_FILES[$KEY]['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Я использовал замену в строке только для проверки моей проблемы: когда я выбираю файл после завершения загрузки, я не могу найти mp3-файл при загрузке без подкачки, я не могу понять, в чем проблема, заранее спасибо