【问题标题】:problem uploading file from Android using multipart使用多部分从 Android 上传文件的问题
【发布时间】:2011-09-27 01:24:11
【问题描述】:

我有以下代码将文件(mpeg 文件 - 大约 20kb)从手机发送到服务器。但是,它在服务器端失败。谁能告诉我我在客户端犯了什么错误?谢谢。

ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //bm.compress(CompressFormat.JPEG, 75, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://example.com/upload.php");
        File file= new File("/mnt/sdcard/enca/aha.mpeg");
        FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new     MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("uploaded", bin);
        reqEntity.addPart("random", new StringBody(encameo1.random));
        reqEntity.addPart("fingerPrint", new StringBody(encameo1.fingerprint));
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        System.out.println("Response: " + s);

php代码:

<?php



$target_path = "uploaded_files/";

$target_path = $target_path . basename( $_FILES['userfile']['name']); 

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) 
{

    echo "The file ".  basename( $_FILES['userfile']['name'])." has been uploaded";

} 

else
{

    echo "There was an error uploading the file, please try again!";

}



?>

【问题讨论】:

    标签: php android file-upload httpclient


    【解决方案1】:

    您正在发送名称为 uploaded 的部件:

    reqEntity.addPart("uploaded", bin);
    

    但是,PHP 需要一个名称为 userfile 的部分:

    if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) 
    

    对齐是一样的。

    【讨论】:

    • 正在将 iOS 应用程序移植到 android 并没有意识到错误。非常感谢。
    猜你喜欢
    • 2016-05-12
    • 2021-01-19
    • 2013-10-12
    • 2018-10-15
    • 1970-01-01
    • 2021-01-01
    • 2015-02-22
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多