0

SDカードからサーバーに画像をアップロードしたい。だから私はバックエンドコード、つまりファイルをアップロードする方法について考えています。しかし、ユーザーが自分のデバイスから画像を選択してサーバーにアップロードする方法を知りたいです。ユーザーに画像を選択してアップロードするように求めるこのアプリケーションの UI を作成するにはどうすればよいですか?アンドロイドが初めてです。画像のアップロードロジックは次のようなものです:私はこのコードを使用している解決策を得ました...

  public class DialogFile extends Activity {
    FileDialog fileDialog = null;
    static String fileName="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        File mPath = new File(Environment.getExternalStorageDirectory() + "//Gaurav-Test//");
        fileDialog = new FileDialog(this, mPath);
        fileDialog.setFileEndsWith(".txt");
        fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
            public void fileSelected(File file) {
                fileName = file.toString();
                Log.d(getClass().getName(), "selected file " + file.toString());
                UploadToServer uploadObj = new UploadToServer();
                try {
                    uploadObj.execute().get();
                } catch (InterruptedException e) {
                    Log.d("InterruptedException", e.getMessage());
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    Log.d("ExecutionException", e.getMessage());
                    e.printStackTrace();
                }
            }
        });
       fileDialog.showDialog();
    }

次に、ファイル FileDilaog.java で

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Environment;
import android.util.Log;


public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    /**
     * @param activity 
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists()) path = Environment.getExternalStorageDirectory();
        loadFileList(path);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
 }

class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();

public interface FireHandler<L> {
    void fireEvent(L listener);
}

public void add(L listener) {
    listenerList.add(listener);
}

public void fireEvent(FireHandler<L> fireHandler) {
    List<L> copy = new ArrayList<L>(listenerList);
    for (L l : copy) {
        fireHandler.fireEvent(l);
    }
}

public void remove(L listener) {
    listenerList.remove(listener);
}

public List<L> getListenerList() {
    return listenerList;
}
}

次に、これをサーバーにアップロードする HTTPOST コード

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;


public class UploadToServer extends AsyncTask<String, String, String>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... aurl){
        String status="";
        final String URL= "";
        Log.d("Image Path ======",DialogFile.fileName);
        try{

        HttpClient httpclient = new DefaultHttpClient();

         HttpPost httppost = new HttpPost(URL);

         File file = new File(DialogFile.fileName);
         FileBody bin = new FileBody(file);
         MultipartEntity reqEntity = new MultipartEntity();
         reqEntity.addPart("userImage", bin);
         httppost.setEntity(reqEntity);
         Log.d("executing request ",  httppost.getRequestLine().toString());
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity resEntity = response.getEntity();

         if (resEntity != null)
         {
            Log.d("Response content length: ",resEntity.getContentLength()+"");
             if(resEntity.getContentLength()>0)
             {
                status= EntityUtils.toString(resEntity);
             }
             else
             {
                 status= "No Response from Server";
                 Log.d("Status----->",status);
             }
     }
     else
     {
          status= "No Response from Server";
          Log.d("Status----->",status);
     }
        } catch (Exception e) {
                e.printStackTrace();
                status="Unable to connect with iPerform server";
            }
            return status;
        }
}
4

3 に答える 3

0

この回答を確認できます https://stackoverflow.com/a/3645048/984466

または、 https://code.google.com/p/android-file-dialog/などのカスタム ファイル ダイアログを使用します 。

于 2013-07-04T06:20:31.350 に答える
0

これを試して:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);

次に、このコードは、ギャラリーから選択した画像を設定することです。ギャラリーから結果を取得するには、onActivityResult メソッドを使用します。

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 1:
                Uri _uri = data.getData();
                String yourimagepath = getRealPathFromURI(_uri);
                ...
                // your code goes here
    }
    super.onActivityResult(requestCode, resultCode, data);
}

public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
}

うまくいけば、それは役に立ちます。

于 2013-07-04T06:23:39.380 に答える
0

このコードは次のことに役立ちます。

    String boundary = "---------------------------14737809831466499882746641449";
    String lineEnd = "\r\n", p;
    String twoHyphens = "--";
    HttpURLConnection conn;
    DataOutputStream dos = null;
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    DataInputStream inStream;
    File sourceFile;
    ArrayList<String> tempList = new ArrayList<String>();

    String exsistingFileName = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/PiyushAushFish";



    try {

        File f = new File(exsistingFileName);

        File[] files = f.listFiles();

        for (int i = 0; i < files.length; i++) {
            File file = files[i];

            tempList.add(file.getPath());
            Log.v("Existing", exsistingFileName);
        }

        // tempList.add(exsistingFileName);
        // tempList.add(FileName);

        if (isUploaded) {

            URL url = new URL(
                    "You URL here");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "text/plain; charset=utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            for (int i = 0; i < tempList.size(); i++) {
                Log.v("Length", tempList.size() + "");
                sourceFile = new File(tempList.get(i));
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                Log.v("IMAGPATH", sourceFile + "");
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);

                System.out
                        .println("==========================image name================="
                                + sourceFile);
                dos.writeBytes("Content-Disposition: form-data; name=\"image[]\"; filename=\""
                        + sourceFile + "\"" + lineEnd);
                dos.writeBytes("Content-Type: application/octet-stream"
                        + lineEnd + lineEnd);
                System.out
                        .println("=============================data writin start================");
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    System.out
                            .println("==============================bytesRead==========================="
                                    + bytesRead);
                }

                dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
                        + lineEnd);
                fileInputStream.close();

            }

            dos.flush();
            dos.close();

        } else {
            Log.v("Error.....", "No Data");
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d("Error--------->", e.getMessage());
        e.printStackTrace();
    }
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            Log.e("Debug", "Server Response " + str);

        }
        inStream.close();

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.e("server response codde", "" + serverResponseCode);
        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
                + ": " + serverResponseCode);
        if (serverResponseCode == 200) {

            isUploaded = true;
            // isUploaded = (c.getInt(23) == 1);

            Log.v("Upload", "Successfully");

        }

    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
于 2013-07-04T06:24:52.203 に答える