在android中上传文件

时间:2014-02-17 18:47:16

标签: java android file-upload

我需要从我的Android应用程序上传一个xml文件到远程主机。我找到了this代码并从here获取了库。但是我收到了这个错误:

02-17 22:06:41.144: E/AndroidRuntime(21644): FATAL EXCEPTION: main
02-17 22:06:41.144: E/AndroidRuntime(21644): java.lang.NoClassDefFoundError:     org.apache.http.entity.mime.HttpMultipart
02-17 22:06:41.144: E/AndroidRuntime(21644):    at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:77)
02-17 22:06:41.144: E/AndroidRuntime(21644):    at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:100)

这是我的上传方法。

private void upload(String filepath)
{
  try
  {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://myurl.com/");
    File file = new File(filepath);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "application/xml");
    mpEntity.addPart("userfile", cbFile);
    httppost.setEntity(mpEntity);

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
  }
  catch(Exception e)
  {
    e.printStackTrace();
  }
}

我使用糟糕的mime类型还是下载错误的库? 有解决方案吗 感谢

1 个答案:

答案 0 :(得分:0)

我找到了一个新的示例here,它使用php脚本将图像上传到php服务器。所以我改了它来上传xml文件。

Android活动:UploadXmlFile.java

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class UploadXmlFile extends Activity {
InputStream inputStream;
ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
String the_string_response;
int contentLength;
String res = "";

    @Override
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_upload_image);

        // create xml content
        String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?><langs><lan><id>1</id><name>java</name></lan><lan><id>2</id><name>c++</name></lan><lan><id>3</id><name>python</name></lan><lan><id>4</id><name>php</name></lan></langs>";

        nameValuePairs.add(new BasicNameValuePair("xmldata",xmldata));
        nameValuePairs.add(new BasicNameValuePair("filename","myfile.xml"));

         Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
              try{
                     HttpClient httpclient = new DefaultHttpClient();
                     HttpPost httppost = new HttpPost("http://your-url.com/upload_xml_file.php");
                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                     HttpResponse response = httpclient.execute(httppost);
                     the_string_response = convertResponseToString(response);
                     runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(UploadXmlFile.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                         
                            }
                        });

                 }catch(final Exception e){
                      runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(UploadXmlFile.this, "Error " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                       Log.d("Error in http connection ",e.toString());
                 } 
        }
    });
     t.start();
    }

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

         StringBuffer buffer = new StringBuffer();
         inputStream = response.getEntity().getContent();
         contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
          runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(UploadXmlFile.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                    
        }
    });

         if (contentLength < 0){
         }
         else{
                byte[] data = new byte[512];
                int len = 0;
                try
                {
                    while (-1 != (len = inputStream.read(data)) )
                    {
                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    inputStream.close(); // closing the stream…..
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                res = buffer.toString();     // converting stringbuffer to string…..

                runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   Toast.makeText(UploadXmlFile.this, "Result : " + res, Toast.LENGTH_LONG).show();
                }
            });
                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
         }
         return res;
    }
}

PHP文件:upload_xml_file.php

<?php
    $base=$_REQUEST['xmldata'];
    $fname=$_REQUEST['filename'];
    header("Content-Type: text/xml; charset=utf-8");
    $file = fopen($fname, 'wb');
    fwrite($file, $base);
    fclose($file);
    echo 'Image upload complete!!, Please check your php file directory……';
?>

在服务器上传php文件并为android应用程序设置INTERNET权限。

希望为别人提供帮助。