Android通过MultipartEntity将图像发送到服务器 - 设置内容类型?

J. *_* K. 9 android

我已经阅读了很多关于从Android应用程序和内容类型向服务器发送图像的帖子,它们分为三类:

a)他们根本不设置内容类型,也可能以某种方式设置他们的代码

b)他们使用弃用的方法

c)他们使用的方法与我选择的完全不同.

我想将文件发送到服务器并将其存储在一个文件夹中.

我的代码是一个完整的拼凑,一个屠宰工作,我在阅读了大量的帖子和文章后设法提出,这里是:

public void uploadImageToServer(String imagePath) throws Exception {

    try {

        // set the http handlers
        httpClient = new DefaultHttpClient();
        localContext = new BasicHttpContext(); // why do I need this?
        postRequest = new HttpPost("http://asd.com/asd.php"); 
        //postRequest.addHeader("Content-type", "image/jpeg"); // - this didnt work

        // deal with the file
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap = BitmapFactory.decodeFile(imagePath);
        bitmap.compress(CompressFormat.JPEG, 75, byteArrayOutputStream); 
        byte[] byteData = byteArrayOutputStream.toByteArray();
        //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this
        ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?)

        // send the package
        multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("uploaded_file", byteArrayBody);

        postRequest.setEntity(multipartEntity.build());

        // get the response. we will deal with it in onPostExecute.
        response = httpClient.execute(postRequest, localContext);
        bitmap.recycle();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

 FATAL EXCEPTION: AsyncTask #1
 java.lang.RuntimeException: An error occured while executing doInBackground()
android.os.AsyncTask$3.done(AsyncTask.java:200)
 java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
java.util.concurrent.FutureTask.setException(FutureTask.java:125)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
java.util.concurrent.FutureTask.run(FutureTask.java:138)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
 java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
 org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:67)
 org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:87)
Run Code Online (Sandbox Code Playgroud)

Ezr*_*rou 5

如果您使用的是库,则需要将其放入/ libs文件夹.

编辑:

从http://hc.apache.org/downloads.cgi下载httpmime,httpcore和httpclient库

  • 不,错误说找不到库内容类型的部分:引起:java.lang.NoClassDefFoundError:org.apache.http.entity.ContentType (2认同)
  • 谢谢,这有助于解决问题.您可以编辑您的答案以将此信息添加到其中.我接受了. (2认同)

hen*_*343 5

使用此代码上传图像文件

HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");
File file = new File(filePath);
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);
StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);

postMethod.setEntity(entity);
client.execute(postMethod);
Run Code Online (Sandbox Code Playgroud)

并在PHP中使用此代码来接收

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo $_POST["contentString"]."\n";
    echo  "File path = ".$uploads_dir;
    move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
    echo "\n Upload Error";
    echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
    print_r($_FILES);
}
Run Code Online (Sandbox Code Playgroud)