Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android上上传mp3到服务器的工作代码_Android_Networking_Upload_Android Volley - Fatal编程技术网

android上上传mp3到服务器的工作代码

android上上传mp3到服务器的工作代码,android,networking,upload,android-volley,Android,Networking,Upload,Android Volley,我已经搜索了所有关于上传mp3或类似文件到php服务器的好代码,并测试了10多个示例,但到目前为止没有一个成功。我签出的大多数代码要么充满bug,要么使用过时的库 如果有人有一个真正的工作代码示例,我将不胜感激。可能是使用截击或类似库的。如果有任何帮助或代码能为我指明正确的方向,我将不胜感激 谢谢您可以使用loopj Android异步Http客户端将文件上载到php服务器。 从给定链接下载lib文件并放入项目的libs文件夹中,然后使用此代码上载文件 public void postFile(

我已经搜索了所有关于上传mp3或类似文件到php服务器的好代码,并测试了10多个示例,但到目前为止没有一个成功。我签出的大多数代码要么充满bug,要么使用过时的库

如果有人有一个真正的工作代码示例,我将不胜感激。可能是使用截击或类似库的。如果有任何帮助或代码能为我指明正确的方向,我将不胜感激


谢谢

您可以使用loopj Android异步Http客户端将文件上载到php服务器。 从给定链接下载lib文件并放入项目的libs文件夹中,然后使用此代码上载文件

public void postFile(){
    RequestParams params = new RequestParams();
    params.put("fileTitle","MyFile1");
    params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

    AsyncHttpClient client = new AsyncHttpClient();

    client.post("http://www.yourweserviceurlhere.com", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                byte[] responseBody, Throwable error) {
            // TODO Auto-generated method stub

        }                                                                                                                                              
    }); 
}
如果您想要上传进度。然后您可以使用我的自定义设计类。为此,在将HTTPresponse转换为字符串时还需要lib引用

public class AsyncLoader {
private String url;
private LoaderCallBackHandler mCallback;
private Context mContext;
private RequestParams params;
private RequestHandle handle;

public interface LoaderCallBackHandler {        
    public void onStartUploading();
    public void uploadComplete(String response);
    public void failedWithError(Throwable error);
    public void progressUpdate(long bytesWritten, long bytesTotal);
    public void onCancle();
    public void onFinish();
}


public AsyncLoader(Context mContext,String url,RequestParams params, LoaderCallBackHandler callback) {
    this.mContext = mContext;
    this.url = url;
    this.params = params;
    this.mCallback = callback;     

}

public void startTransfer() {       
    AsynchConfig.mClient.setTimeout(50000);        
    handle = AsynchConfig.mClient.post(mContext, url, params,handlerInterface);
}    
private ResponseHandlerInterface handlerInterface = new ResponseHandlerInterface() {

    @Override
    public void sendStartMessage() {
        if(mCallback != null) {
            mCallback.onStartUploading();               
        }

    }

    @Override
    public void sendResponseMessage(HttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();

            // TODO convert in stream to JSONObject and do whatever you need to

            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer, Charset.defaultCharset());
            String theString = writer.toString();

            if(mCallback != null) {
                mCallback.uploadComplete(theString);
            }
        }

    }

    @Override
    public void sendSuccessMessage(int arg0, org.apache.http.Header[] arg1, byte[] arg2) {

    }

    @Override
    public void sendFailureMessage(int arg0, org.apache.http.Header[] arg1,
            byte[] arg2, Throwable error) {
            if(mCallback != null) {
                 mCallback.failedWithError(error);
            }
    }

    @Override
    public void sendFinishMessage() {
        if(mCallback != null) {
            mCallback.onFinish();
        }
    }

    @Override
    public void sendProgressMessage(long bytesWritten, long bytesTotal) {
        if(mCallback != null) {             
            mCallback.progressUpdate(bytesWritten, bytesTotal);
        }

    }

    @Override
    public void setUseSynchronousMode(boolean arg0) {
    }

    @Override
    public void setRequestURI(URI arg0) {
    }

    @Override
    public void setRequestHeaders(org.apache.http.Header[] arg0) {
    }

    @Override
    public URI getRequestURI() {
        return null;
    }
    @Override
    public org.apache.http.Header[] getRequestHeaders() {
        return null;
    }

    @Override
    public void sendCancelMessage() {

        if(mCallback != null) {
            mCallback.onCancle();
            mCallback.onFinish();
        }
    }

    @Override
    public void sendRetryMessage(int retryNo) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean getUseSynchronousMode() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void setUsePoolThread(boolean usePoolThread) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean getUsePoolThread() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onPreProcessResponse(ResponseHandlerInterface instance,
            HttpResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPostProcessResponse(ResponseHandlerInterface instance,
            HttpResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setTag(Object TAG) {
        // TODO Auto-generated method stub

    }

    @Override
    public Object getTag() {
        // TODO Auto-generated method stub
        return null;
    }
};

/**
* Cancel upload by calling this method
*/
public void cancel() throws Exception {
    AsynchConfig.mClient.cancelAllRequests(true);
    handle.cancel(true);

}
}
异步配置类

public final class AsynchConfig {   
     public static AsyncHttpClient mClient = new AsyncHttpClient();
}
使用

RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

AsyncLoader asyncUploader = new AsyncLoader(this, "URL_HERE", params, callHandler);
asyncUploader.startTransfer();
if(isset($_FILES['file']) && isset($_POST['fileTitle']) ) {
include './config.php';

//Randomly genrate file name
$stickerTmp = explode(".", $_FILES["file"]["name"]);
$file = md5(date("l, F d, Y h:i" ,time()) . (microtime())).".".end($stickerTmp);

//geting the temp location of file
$filetemploc=$_FILES['file']['tmp_name']; 

//path for uploading to the specific location
$pathandname="file_store/".$file;

// moving the file to specified path
$resultUpload = move_uploaded_file($filetemploc, $pathandname);

// if file is successfully moved to over specified path then insert the reference into the DB
if($resultUpload == TRUE) {
    //echo "File has been moved from : ". $filetemploc . " to  :".$pathandname;

    $qInsert = "INSERT INTO file_lists values (null,'".$_POST['fileTitle']."','".$file."') ";
    mysql_query($qInsert);
}

}
CallHandler接口对象

LoaderCallBackHandler callHandler = new LoaderCallBackHandler() {

    @Override
    public void uploadComplete(String response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void progressUpdate(long bytesWritten, long bytesTotal) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStartUploading() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCancle() {
        // TODO Auto-generated method stub

    }

    @Override
    public void failedWithError(Throwable error) {
        // TODO Auto-generated method stub

    }
};
处理上传文件的PHP服务

RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

AsyncLoader asyncUploader = new AsyncLoader(this, "URL_HERE", params, callHandler);
asyncUploader.startTransfer();
if(isset($_FILES['file']) && isset($_POST['fileTitle']) ) {
include './config.php';

//Randomly genrate file name
$stickerTmp = explode(".", $_FILES["file"]["name"]);
$file = md5(date("l, F d, Y h:i" ,time()) . (microtime())).".".end($stickerTmp);

//geting the temp location of file
$filetemploc=$_FILES['file']['tmp_name']; 

//path for uploading to the specific location
$pathandname="file_store/".$file;

// moving the file to specified path
$resultUpload = move_uploaded_file($filetemploc, $pathandname);

// if file is successfully moved to over specified path then insert the reference into the DB
if($resultUpload == TRUE) {
    //echo "File has been moved from : ". $filetemploc . " to  :".$pathandname;

    $qInsert = "INSERT INTO file_lists values (null,'".$_POST['fileTitle']."','".$file."') ";
    mysql_query($qInsert);
}

}

谢谢我们将尽快试用,但如果您能添加PHP代码在服务器上接收文件,我们将不胜感激。谢谢。我刚要发布,它实际上与我自己的php代码一起工作。这是迄今为止我看到的最好、最简单的文件上传代码。如此简单和快速。再次感谢。我还没有尝试过你的自定义类,但是函数运行得很好。也将尝试它的大文件,看看它如何进行。