如何在android中发布文件上传的键/值对

时间:2011-11-08 14:44:59

标签: java android multipartform-data

我知道这是重复的问题。堆栈溢出中有很多类似的问题,但我问这个问题,因为我不明白如何用Image发布一些数据。

我想将带有图像的名字和姓氏传递给服务器。 我现在还是试过这个。

URL connectURL;
connectURL = new URL("some URL");
File sdImageMainDirectory = new File("/sdcard");
String existingFileName = sdImageMainDirectory.toString() +"/image.jpg";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
try
{
    HttpURLConnection conn = (HttpURLConnection) connectURL.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);

    DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"firstname\"" + lineEnd);
    dos.writeBytes("Dharmendra");
    dos.writeBytes(lineEnd);

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"lastname\"" + lineEnd);
    dos.writeBytes("Patel");
    dos.writeBytes(lineEnd);

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
    dos.writeBytes(lineEnd);

    int bytesAvailable = fileInputStream.available();
    int maxBufferSize = 1024;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    int 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);
    }
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    fileInputStream.close();
    dos.flush();
    dos.close();
}catch (MalformedURLException ex) {
    Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
    Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}

2 个答案:

答案 0 :(得分:11)

检查此代码以添加其他值以将图像上传到服务器:

public class Task_TurnoutPost extends AsyncTask<Void, Void, Void> {
        private final ProgressDialog dialog = new ProgressDialog(ActivityName.this);
        JSONObject object_feed;
        // can use UI thread here
        protected void onPreExecute() {
            this.dialog.setMessage("Loading...");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost("Your LINK");
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("F_Name", new StringBody("F_Name"));
                reqEntity.addPart("L_Name",new StringBody("L_NAME"));
                try{
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(CompressFormat.JPEG, 75, bos);
                    byte[] data = bos.toByteArray();
                    ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
                    reqEntity.addPart("picture", bab);
                }catch(Exception e){
                    //Log.v("Exception in Image", ""+e);
                    reqEntity.addPart("picture", new StringBody(""));
                }

                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();
                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                object_feed = new JSONObject(s.toString());
                success_response=object_feed.getString("status");
                Log.v("Response for POst", s.toString());
            } catch (Exception e) {
                Log.e("e.getClass().getName()", ""+e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
        }

    }

位图是你的位图。除此之外,还添加了一个库和download it

Check this for you reference

答案 1 :(得分:0)

我实际上会在这里使用Http标头来发布键值对。喜欢这个

conn.setRequestProperty("firstName", "Stephen");
conn.setRequestProperty("lastName", "glansburg");

然后在服务器端,您可以查看该元信息的http标头。