【问题标题】:Upload picture to server上传图片到服务器
【发布时间】:2025-12-31 16:25:14
【问题描述】:

我用谷歌搜索了很多,但它不起作用。我发现了很多有信息的网站,但是我的应用程序在所有网站上都崩溃了。我要打开的图片是:“lastfile.png”。它存储在内部存储中,所以我用 openFileInput("lastfile.png"); 来打开它;

我在 AsyncTask 中完成。

这是我目前的代码:

class PostTask extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... uri) {
            if(picture == null) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response;
                String responseString = null;
                try {
                    response = httpclient.execute(new HttpGet(uri[0]));
                    StatusLine statusLine = response.getStatusLine();
                    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                    } else{
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (ClientProtocolException e) {
                    Toast.makeText(AddStoryActivity.this, getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } catch (IOException e) {
                    Toast.makeText(AddStoryActivity.this, getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                return responseString;
            } else {
                /* IMAGE UPLOAD */
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progress.cancel();
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();       
        }


    }

【问题讨论】:

  • 要上传的图片数据在哪里?这似乎更像是一种从服务器 dnload 的方式。对于图片上传,您应该创建一个 HttpPost 请求,并在调用 httpClient.execute 之前将要上传的文件附加到它。

标签: java android file-upload


【解决方案1】:

我这样做的方法是将 img 压缩为一种字符串类型,然后将其作为名称值对发送,然后使用 php 在服务器端解码字符串。

Bitmap bitmapOrg = BitmapFactory.decodeResource("你在设备上的图片路径");

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte [] ba = bao.toByteArray();
        String ba1= Base64.encodeToString(ba, 0);
         ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));

try{

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://your_url/sink.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
          }catch(Exception e){

                Log.e("log_tag", "Error in http connection "+e.toString());
          } 

SINK.PHP

<?php

$base=$_REQUEST['image'];
$name=$_REQUEST['name'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');


$file = fopen(name, 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src='+name+'>';

?>

【讨论】: