上传图片到服务器 [英] Upload picture to server

查看:392
本文介绍了上传图片到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我GOOGLE了很多,但它不工作。我发现很多网站的信息,但所有的网站我的应用程序崩溃。我想开图片:lastfile.png。它存储在内部存储,所以我用openFileInput打开它(lastfile.png);

我这样做是在一个AsyncTask的。

这是我的code到目前为止:

 类PostTask扩展的AsyncTask<字符串,字符串,字符串> {
        @覆盖
        保护字符串doInBackground(字符串... URI){
            如果(图片== NULL){
                HttpClient的HttpClient的=新DefaultHttpClient();
                HTT presponse响应;
                字符串responseString = NULL;
                尝试 {
                    响应= httpclient.execute(新HTTPGET(URI [0]));
                    状态行状态行= response.getStatusLine();
                    如果(statusLine.getStatus code()== HttpStatus.SC_OK){
                        ByteArrayOutputStream OUT =新ByteArrayOutputStream();
                        。response.getEntity()的writeTo(出);
                        out.close();
                        responseString = out.toString();
                    } 其他{
                        。response.getEntity()的getContent()close()方法。
                        抛出新IOException异常(statusLine.getReasonPhrase());
                    }
                }赶上(ClientProtocolException E){
                    Toast.makeText(AddStoryActivity.this,getResources()的getString(R.string.error),Toast.LENGTH_LONG。).show();
                    e.printStackTrace();
                }赶上(IOException异常E){
                    Toast.makeText(AddStoryActivity.this,getResources()的getString(R.string.error),Toast.LENGTH_LONG。).show();
                    e.printStackTrace();
                }
                返回responseString;
            } 其他 {
                / *图片上传* /
            }
            返回 ;
        }

        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);
            progress.cancel();
            Toast.makeText(getApplicationContext(),结果,Toast.LENGTH_LONG).show();
        }


    }
 

解决方案

我做的是COM preSS到一个字符串类型的IMG然后将其发送的名称值对,然后去code的方式使用PHP服务器端的字符串。

位图bitmapOrg = BitmapFactory.de codeResource(你的形象路径上的设备);

  ByteArrayOutputStream宝=新ByteArrayOutputStream();
        bitmapOrg.com preSS(Bitmap.Com pressFormat.JPEG,90,宝);
        byte []的BA = bao.toByteArray();
        字符串BA1 = Base64.en codeToString(BA,0);
         ArrayList的<的NameValuePair> namevaluepairs中=新
ArrayList的<的NameValuePair>();
            nameValuePairs.add(新BasicNameValuePair(形象,BA1));

尝试{

                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httppost =新HttpPost(HTTP://your_url/sink.php);
                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();
          }赶上(例外五){

                Log.e(log_tag,错误的HTTP连接+ e.toString());
          }
 

SINK.PHP

 < PHP

$基地= $ _ REQUEST ['形象'];
$名称= $ _ REQUEST ['名称'];
回声$基地;
// EN BASE64 codeD UTF-8字符串
$二进制= base64_de code($基地);
//二进制,UTF-8字节
标题(内容类型:位图;字符集= UTF-8);


$文件= FOPEN(名字,世行);
FWRITE($文件,$二);
fclose函数($文件);
回声'< IMG SRC ='+名字+'>';
 

?>

I've googled a lot but it doesn't work. I found a lot of sites with information but by all the sites my app crashed. The picture that I want to open is: "lastfile.png". It is stored in internal storage so I open it with openFileInput("lastfile.png");

I do it in in an AsyncTask.

This is my code so far:

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();       
        }


    }

解决方案

The way I did it was to compress the img in to a type of string then send it as name value pair then decode the string on server end using php.

Bitmap bitmapOrg = BitmapFactory.decodeResource("your image path on device");

        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+'>';

?>

这篇关于上传图片到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆