duanchui1251 2016-03-03 08:33
浏览 53

使用Android上的HttpUrlConnection,通过apache中的php文件将映像上传到服务器

In my application I am attempting to upload a photo to my server via a LAN connection. I started with this tutorial: Sending Image to Server, but found out that it used deprecated methods - HttpParams & HttpClient to be specific. Upon searching, I found HttpUrlConnection, and am trying to fix the app to upload a photo.

Here is my Android Code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private static final int RESULT_LOAD_IMAGE = 1;
private static final String SERVER_ADDRESS = "http://my__LAN_IP_address/SavePicture.php";
HttpURLConnection urlConnection = null;

ImageView imageToUpload, downloadedImage;
Button bUploadImage, bDownloadImage;
EditText uploadImageName, downLoadImageName;
InputStream is;


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

    imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
    downloadedImage = (ImageView) findViewById(R.id.downloadedImage);

    bUploadImage = (Button) findViewById(R.id.bUploadImage);
    bDownloadImage = (Button) findViewById(R.id.bDownloadImage);

    uploadImageName = (EditText) findViewById(R.id.etUploadImage);
    downLoadImageName = (EditText) findViewById(R.id.etDownloadName);

    imageToUpload.setOnClickListener(this);
    bUploadImage.setOnClickListener(this);
    bDownloadImage.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.imageToUpload:
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
            break;
        case R.id.bUploadImage:
            Bitmap image = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();
            new UploadImage(image, uploadImageName.getText().toString()).execute();
            break;
        case R.id.bDownloadImage:

            break;

    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
        Uri selectedImage = data.getData();
        imageToUpload.setImageURI(selectedImage);
    }
}

private class UploadImage extends AsyncTask<Void, Void, Void>{

    Bitmap image;
    String name;

    public UploadImage(Bitmap image, String name){
        this.image = image;
        this.name = name;
    }

    @Override
    protected Void doInBackground(Void... params) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
        ContentValues dataToSend = new ContentValues();
        dataToSend.put("image", encodedImage);
        dataToSend.put("name", name);
        try{
            URL url = new URL(SERVER_ADDRESS);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(3000);
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(String.valueOf(dataToSend));
            writer.flush();
            writer.close();
            os.close();
            connection.connect();
            is = connection.getInputStream();


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(getApplicationContext(), "Image Uploaded", Toast.LENGTH_SHORT).show();
    }
}
}

And here is my php code:

<?php

$name = isset($_POST["name"]) ? $_POST["name"] : '';
$image = isset($_POST["image"]) ? $_POST["image"] : '';


$decodedImage = base64_decode("$image");
file_put_contents("pictures/" + $name + ".JPG", $decodedImage);

?>

Upon running the app and selecting a photo, nothing errors out and it seems to work, but looking server side, there are no photos getting uploaded. Any help would be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • doubeiji2602 2016-03-03 08:54
    关注

    Use this

    //File path 
    String filepath = ""
    
    @Override
    protected String doInBackground(Void... params) {
        String responseString = null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "
    ";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead;
        long sentData = 0;
    
        //URL
        String urlString = ""
    
        try {
            UUID uniqueKey = UUID.randomUUID();
            String fname = uniqueKey.toString();
            FileInputStream fileInputStream = new FileInputStream(new File(filePath));
            int length = fileInputStream.available();
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setChunkedStreamingMode(1024);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+ (new File(filePath)).getName()+"\"" + lineEnd);
            dos.writeBytes(lineEnd);
    
            int maxBufferSize = 1024;
            int bufferSize = Math.min(length, maxBufferSize);
            byte[ ] buffer = new byte[bufferSize];
            bytesRead = 0;
            int latestPercentDone;
            int percentDone = -1;
    
            bytesRead =  fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bytesRead);
                sentData += bytesRead;
                latestPercentDone = (int) ((sentData / (float) length) * 100);
                if (percentDone != latestPercentDone) {
                    percentDone = latestPercentDone;
                    publishProgress(percentDone);
                }
                int bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            fileInputStream.close();
            dos.flush();
            dos.close();
    
        } catch (MalformedURLException ex) {
    
        } catch (IOException ioe) {
    
        }
    
        try {
            statusCode = conn.getResponseCode();
    
            if (statusCode == 200) {
                responseString = "File Uploaded";
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }
    
    
        } catch (IOException ioex) {
            responseString = ioex.getMessage();
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
    
        super.onPostExecute(result);
        System.out.println(result)
    }
    

    Also, try writing the file somewhere before uploading. It will be useful if the upload fails and you want to retry later.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决