使用Koush Ion库上传多部分文件

4

在我的最新应用中,我将使用Koush Ion库。这个库很方便,但是我在上传文件到我的REST服务器时遇到了问题。 注意:我的服务器响应成功上传的过程是1。

我的代码如下:

public class MainActivity extends Activity {

    Button upload, login;
    TextView uploadCount;
    ProgressBar progressBar;
    String token, FilePath;

    Future<String> uploading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        upload      = (Button) findViewById(R.id.upload);
        uploadCount = (TextView) findViewById(R.id.upload_count);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        token       = "147c85ce29dc585966271280d59899a02b94c020";
        FilePath    = Environment.getExternalStorageDirectory().toString()+"/police.mp3";


        upload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (uploading !=null && !uploading.isCancelled()){
                    resetUpload();
                    return;
                }

                upload.setText("Uploading...");

                uploading = Ion.with(MainActivity.this)
                            .load("http://myserver.com/api/v1/tone/upload/?token="+token)
                            .setLogging("UPLOAD LOGS:", Log.DEBUG)
                            .uploadProgressBar(progressBar)
                            .uploadProgressHandler(new ProgressCallback() {

                                @Override
                                public void onProgress(int downloaded, int total) {
                                    uploadCount.setText("" + downloaded + "/" + total);

                                }
                            })
                            .setMultipartParameter("title", "police")
                            .setMultipartParameter("category", "7")
                            .setMultipartFile("file_url", new File(FilePath))
                            .asString()
                            .setCallback( new FutureCallback<String>() {

                                @Override
                                public void onCompleted(Exception e, String result) {
                                    // TODO Auto-generated method stub

                                }
                            })
                            ;
            }
        });

但是我从服务器得到了TimeoutException错误。 我的问题是: 1.我的文件选择方式是否正确?! 2.我应该使用Future Callback作为字符串吗?!
我通过Fiddler2检查了对服务器的请求,当我尝试上传文件到服务器时...它向我显示请求已发送,multipartParameters已发送,但是当尝试发送文件时... Fiddler向我显示错误:
Protocol Violation Report:
Content-Length mismatch: Request Header indicated 455 bytes, but client sent 387 bytes.

你使用的ion版本是什么?你的服务器后端是什么?其他使用ion的http调用是否正常工作? - koush
@koush 最新的版本,是的,我可以进行 HTTP 调用(我可以发送 JSON 对象并获取 JSON 对象作为结果)......请帮帮我。非常感谢 :) - MAY3AM
嘿,你解决了这个问题吗?我也遇到同样的情况。 - Danpe
@Danpe,这个问题还没有解决,是一个开放的问题。https://github.com/koush/ion/issues/362 - MAY3AM
2个回答

7

这对我来说实际上很有效,以下是我的代码:

final File fileToUpload = new File(localFilePath);
Ion.with(context)
            .load(Urls.UPLOAD_PICTURE)
            .uploadProgressHandler(new ProgressCallback() {
                @Override
                public void onProgress(long uploaded, long total) {
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(notificationId, mBuilder.build());
                    mBuilder.setProgress((int) total, (int) uploaded, false);
                }
            })
            .setTimeout(60 * 60 * 1000)
            .setMultipartFile("upload", "image/jpeg", fileToUpload)
            .asJsonObject()
                    // run a callback on completion
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    // When the loop is finished, updates the notification
                    mBuilder.setContentText("Upload complete")
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    mNotifyManager.notify(notificationId, mBuilder.build());
                    if (e != null) {
                        Toast.makeText(context, "Error uploading file", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Toast.makeText(context, "File upload complete", Toast.LENGTH_LONG).show();
                }
            });
}

希望对某人有所帮助 :)

谢谢,我现在正在使用Loopj库来完成我的应用程序的这一部分,我会在第一次发布后采用你的解决方案。 - MAY3AM
在 Urls.UPLOAD_PICTURE 中,您是在服务器上使用脚本还是指向服务器上的文件夹? - ymerdrengene

3

我搜索了很久才发现,重要的是在 .load() 中包含 POST。

Ion.with(getBaseContext()).load("POST",url).uploadProgressHandler(new ProgressCallback()
        {
            @Override
            public void onProgress(long uploaded, long total)
            {
                System.out.println("uploaded " + (int)uploaded + " Total: "+total);
            }
        }).setMultipartParameter("platform", "android").setMultipartFile("image", new File(getPath(selectedImage))).asString().setCallback(new FutureCallback<String>()
        {
            @Override
            public void onCompleted(Exception e, String result)
            {

            }
        });

似乎很合理将其包含在内,但对我来说并不是必要的。 - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接