在android中从SD卡上传文件到Web服务器

时间:2011-03-24 19:13:25

标签: java android

大家。我正在尝试将图片文件从手机上传到我的计算机上的Apache Web服务器,但没有成功。这是我的代码:

package com.testconnectivity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String pathToOurFile = "/sdcard/Confused.jpg";
        String urlServer = "http://190.213.29.178/connectiontest1.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;

        try
        {
        FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0)
        {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
       String serverResponseMessage = connection.getResponseMessage();

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        }
        catch (Exception ex)
        {
        //Exception handling
         Log.d("MainActivity", "Print " + ex.toString());

        }

    }
}

// connectiontest1.php

<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>

有人可以告诉我这是什么问题吗?我需要一个Web服务还是其他一些问题?任何帮助将非常感激。

2 个答案:

答案 0 :(得分:0)

你得到android.os.NetworkOnMainThreadException吗? 您应该尝试使用AsyncTask。这对我有用。
检查一下:How to fix android.os.NetworkOnMainThreadException?

答案 1 :(得分:0)

在此代码下方:

//启用POST方法         connection.setRequestMethod( “POST”);

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form data;boundary="+boundary);

添加以下行:

connection.setRequestProperty(“uploadedfile”,pathToOurFile);