Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何将图像添加到web服务器_Android_File Upload - Fatal编程技术网

Android 如何将图像添加到web服务器

Android 如何将图像添加到web服务器,android,file-upload,Android,File Upload,在这里我想上传图片到网站上 我列出了代码,但它不起作用 请帮我纠正一下 MyImageUploader.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.i

在这里我想上传图片到网站上

我列出了代码,但它不起作用

请帮我纠正一下

MyImageUploader.java

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyImageUploader extends Activity{
    private static final int PICK_IMAGE = 1;
    private ImageView imageview;
    private TextView textview;
    private Button button;
    private EditText edittext;
    private Bitmap bitmap;
    private ProgressDialog dialog;
    String albumId = ConstantData.album_id;
    Integer userId = ConstantData.userId;
    Bitmap photoId; 
    ArrayList<Object> result;
    XmlParser parser;
    HttpResponse response;
    InputStream in;
    String strResponse;
    HttpPost post;
    int width_tmp,height_tmp;
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myimageuploader);

        imageview = (ImageView)findViewById(R.id.upldimgvw);
        button = (Button)findViewById(R.id.btn_imgupld);
        edittext = (EditText)findViewById(R.id.edt_cptn);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(bitmap == null){
                    Toast.makeText(getApplicationContext(), "Please select image..", Toast.LENGTH_SHORT).show();
                }
                else{
                    dialog = ProgressDialog.show(MyImageUploader.this, "Uploading", "Please wait...",true);
                    new ImageUploadTask().execute();
                }
            }
        });
    }
     public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.imageupload_menu, menu);
        return true;
    }
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
            case R.id.ic_menu_gallery:
                try{
                    Intent intent = new Intent();
                    intent.setType("Image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
                }catch (Exception e) {
                // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "Get Picture" ,Toast.LENGTH_SHORT).show();
                    Log.e(e.getClass().getName(),e.getMessage(),e);
                    break;
                }
                return true;
            case R.id.ic_menu_Images:     
                Toast.makeText(this, "You pressed the Image!", Toast.LENGTH_LONG).show();
                break;
         }
        return super.onOptionsItemSelected(item);
        }

    protected void onActivityResult(int requestcode,int resultcode, Intent data){
        Log.i("Request Code",""+requestcode);
        Log.i("Result Code", ""+resultcode);
        Log.i("Intent Data",""+data);
        switch(requestcode){
        case PICK_IMAGE:
            if(resultcode == Activity.RESULT_OK);
            Uri selectedImageUri = data.getData();
            String filePath = null;
            try{
                String filemanagerstring = selectedImageUri.getPath();
                String selectedImagePath = getPath(selectedImageUri);
                if(selectedImagePath != null)
                {
                    filePath = selectedImagePath;
                }else if(filemanagerstring != null)
                {
                    filePath = filemanagerstring;
                }else{
                    Toast.makeText(getApplicationContext(), "Unknown Path",Toast.LENGTH_SHORT).show();
                    Log.e("Bitmap","Unknown Path");
                }
                if(filePath != null){
                    decodeFile(filePath);
                }
                else{
                    bitmap = null;
                }
            }catch (Exception e) {
                // TODO: handle exception
                Toast.makeText(getApplicationContext(), "Internal Error", Toast.LENGTH_SHORT);
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }   

    }

    class ImageUploadTask extends AsyncTask<Void, Void, String>{
        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
                try{
                    DefaultHttpClient client = new DefaultHttpClient();
                    post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=album_list&upload_photo&userid=80&sessionid=3011e063260d55b8a7095bc3a581130c&tmpl=component 14:34");
                    StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><photo>"+photoId+"</photo></data>");
                    StringEntity strEntity = new StringEntity(strBuffer.toString());
                    post.setEntity(strEntity);

                    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(CompressFormat.JPEG, 100, bos);
                    byte[] data = bos.toByteArray();
                    entity.addpart("userId");
                    entity.addPart("albumId");
                    entity.addPart("photoId", new FileBody(new File(filepath)));
                    post.setEntity(entity);
                    response = client.execute(post);
                    in = response.getEntity().getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                    strResponse = convertStreamToString(in);
                    parser = new XmlParser(in, new AddAlbumDetailBean());
                    result = parser.parse("data", "photo");
                }catch (Exception e){
                    if (dialog.isShowing())
                        dialog.dismiss();
                        Toast.makeText(getApplicationContext(),"image",Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
            return null;
        }
                return albumId;
        }
        }
    protected void onPostExecution(String strResponse){
            try{
                if(dialog.isShowing())
                    dialog.dismiss();
                if(strResponse != null)
                {
                    Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getApplicationContext(), "Photo Uploaded Successfully", Toast.LENGTH_SHORT).show();
                    edittext.setText("");
                }


                }catch (Exception e) {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(),"Exception Image", Toast.LENGTH_SHORT).show();
                                Log.e(e.getClass().getName(), e.getMessage(), e);
                }
    }


    public String getPath(Uri uri){
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor != null){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else{
            return null;
        }
    }
    public void decodeFile(String filePath){
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath,o);

        final int REQUEST_SIZE = 1024;
        int width_tmp = o.outWidth,height_tmp = o.outHeight;
        int scale = 1;
        while(true){
        //  if(width_tmp &lt;REQUEST_SIZE &amp;&amp; height_tmp &lt; REQUEST_SIZE){
                //break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
        //  }
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFile(filePath,o2);
            imageview.setImageBitmap(bitmap);
        }

    }
    public String convertStreamToString(InputStream in)
    throws IOException {


        if (in != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(in, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                // in.close();
            }
            return writer.toString();
        } else { 
            return "";
        }
    }
}
导入java.io.BufferedReader;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.Reader;
导入java.io.StringWriter;
导入java.io.Writer;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.protocol.BasicHttpContext;
导入org.apache.http.protocol.HttpContext;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.database.Cursor;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Bitmap.CompressFormat;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.provider.SyncStateContract.Constants;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuInflater;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MyImageUploader扩展活动{
私有静态最终整型拾取图像=1;
私人影像视图;
私有文本视图文本视图;
私人按钮;
私人编辑文本;
私有位图;
私人对话;
字符串albumId=ConstantData.album\u id;
整数userId=ConstantData.userId;
位图照片;
阵列列表结果;
XmlParser;
HttpResponse响应;
输入流输入;
字符串响应;
HttpPost;
整数宽度\u tmp,高度\u tmp;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myimageuploader);
imageview=(imageview)findViewById(R.id.upldimgvw);
按钮=(按钮)findViewById(R.id.btn_imgupld);
edittext=(edittext)findViewById(R.id.edt_cptn);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
如果(位图==null){
Toast.makeText(getApplicationContext(),“请选择图像…”,Toast.LENGTH\u SHORT.show();
}
否则{
dialog=ProgressDialog.show(MyImageUploader.this,“正在上载”,“请稍候…”,true);
新建ImageUploadTask().execute();
}
}
});
}
公共布尔onCreateOptions菜单(菜单){
MenuInflater充气机=getMenuInflater();
充气机。充气(右菜单。图像上传菜单,菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.ic\U菜单\U图库:
试一试{
意图=新意图();
intent.setType(“Image/*”);
intent.setAction(intent.ACTION\u GET\u CONTENT);
startActivityForResult(Intent.createChooser(Intent,“选择图片”),PICK_IMAGE);
}捕获(例外e){
//TODO:处理异常
Toast.makeText(getApplicationContext(),“获取图片”,Toast.LENGTH\u SHORT.show();
Log.e(e.getClass().getName(),e.getMessage(),e);
打破
}
返回true;
案例R.id.ic_菜单_图像:
Toast.makeText(这是“您按下了图像!”,Toast.LENGTH_LONG.show();
打破
}
返回super.onOptionsItemSelected(项目);
}
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
Log.i(“请求代码”,“请求代码”);
Log.i(“结果代码”,“结果代码”);
Log.i(“意图数据”,即“+”数据);
开关(请求代码){
案例选取图像:
if(resultcode==Activity.RESULT\u OK);
Uri selectedImageUri=data.getData();
字符串filePath=null;
试一试{
字符串filemanagerstring=selectedImageUri.getPath();
字符串selectedImagePath=getPath(selectedImageUri);
如果(selectedImagePath!=null)
{
filePath=selectedImagePath;
}else if(filemanagerstring!=null)
{
filePath=filemanagerstring;
}否则{
Toast.makeText(getApplicationContext(),“未知路径”,Toast.LENGTH\u SHORT.show();
Log.e(“位图”,“未知路径”);
}
if(filePath!=null){
解码文件(文件路径);
}
否则{
位图=空;
}
}捕获(例外e){
//TODO:处理异常
Toast.makeText(getApplicationContext(),“内部错误”,Toast.LENGTH\u SHORT);
Log.e(e.getClass().getName(),e.getMessage(),e);
}
}   
}
类ImageUploadTask扩展了AsyncTask{
@凌驾
受保护字符串doInBackground(无效…参数){
//TODO自动生成的方法存根
试一试{
DefaultHttpClient=新的DefaultHttpClient();
post=新的HttpPost(“http://192.168.5.10/ijoomer_development/index.php?option=com_ijoome
public void uploadImage(String fileName)
{
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = GlobalHandler.getImageUploadUrl();
    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);
    if(GlobalHandler.getUserId()!=null)
        connection.addRequestProperty("user_id", GlobalHandler.getUserId());
    else
        connection.addRequestProperty("user_id", "007");

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"upload_file\";  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

    }

}