如何在android中使用图像和文本创建多部分表单数据?

如何在android中使用图像和文本创建多部分表单数据?,android,multipartform-data,fileinputstream,Android,Multipartform Data,Fileinputstream,我正在构建一个应用程序,在某一点上,我需要上传一个图像到服务器。 当我只把图像作为一个参数时,一切都很完美,但问题是当我添加文本时,什么也没有发生。这是我的密码 public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null;

我正在构建一个应用程序,在某一点上,我需要上传一个图像到服务器。 当我只把图像作为一个参数时,一切都很完美,但问题是当我添加文本时,什么也没有发生。这是我的密码

public int uploadFile(String sourceFileUri) {
      String fileName = sourceFileUri;
      HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(sourceFileUri); 
        try { 

            // open a URL connection to the Servlet
          FileInputStream fileInputStream = new FileInputStream(sourceFile);
          URL url = new URL(upLoadServerUri);

          // Open a HTTP  connection to  the URL
          conn = (HttpURLConnection) url.openConnection(); 
          conn.setDoInput(true); // Allow Inputs
          conn.setDoOutput(true); // Allow Outputs
          conn.setUseCaches(false); // Don't use a Cached Copy
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setRequestProperty("ENCTYPE", "multipart/form-data");
          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
          conn.setRequestProperty("uploaded_file", fileName); 
          conn.setRequestProperty("username", username); 
          dos = new DataOutputStream(conn.getOutputStream());

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

          dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\""
                                    + username + "\"" + lineEnd);
          dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
          dos.writeBytes(lineEnd);

          // create a buffer of  maximum size
          bytesAvailable = fileInputStream.available(); 

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

          // read file and write it into form...
          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);   

           }

          // send multipart form data necesssary after file data...
          dos.writeBytes(lineEnd);
          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

          // Responses from the server (code and message)
          serverResponseCode = conn.getResponseCode();
          String serverResponseMessage = conn.getResponseMessage();

          Log.i("uploadFile", "HTTP Response is : " 
                  + serverResponseMessage + ": " + serverResponseCode);

          if(serverResponseCode == 200){

              runOnUiThread(new Runnable() {
                   public void run() {

                       String msg = "http://phpserver"+ture;


                       Toast.makeText(Friend.this, "Uploaded succesfully", 
                                    Toast.LENGTH_SHORT).show();
                       //new Post_test().execute();
                   }
               });                
          }    

          //close the streams //
          fileInputStream.close();
          dos.flush();
          dos.close();

     } catch (MalformedURLException ex) {

         dialog.dismiss();  
         ex.printStackTrace();

         runOnUiThread(new Runnable() {
             public void run() {

                 Toast.makeText(Friend.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
             }
         });

         Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
     } catch (Exception e) {

         dialog.dismiss();  
         e.printStackTrace();

         runOnUiThread(new Runnable() {
             public void run() {

                 Toast.makeText(Friend.this, "Got Exception : see logcat ", 
                         Toast.LENGTH_SHORT).show();
             }
         });
         Log.e("Upload file to server Exception", "Exception : " 
                                          + e.getMessage(), e);  
     }
     dialog.dismiss();       

    return serverResponseCode; 
}
我做错了什么

当我删除:

dos.writeBytes(twoHyphens + boundary + lineEnd);          
dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\"" + 
                username + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
图像被上传,因此问题可能来自如何添加文本帖子。
有什么帮助吗?

这对我有用!!我将在将来调整它以适应URLConnection

public int uploadFile(String sourceFileUri) {  

    String fileName=sourceFileUri;
    HttpURLConnection conn = null;
    DataOutputStream dos = null;  
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "------hellojosh";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(fileName); 
    Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);

    if (!sourceFile.isFile()) {                                
         Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);                
         runOnUiThread(new Runnable() {
            public void run() {             
                //messageText.setText("Source File not exist :"
                }
            });          
         return 0;  //RETURN #1
         }
    else{
        try{                

             FileInputStream fileInputStream = new FileInputStream(sourceFile);           
             URL url = new URL(upLoadServerUri);
             Log.v("joshtag",url.toString());

             // Open a HTTP  connection to  the URL
             conn = (HttpURLConnection) url.openConnection(); 
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy            s       
             conn.setRequestMethod("POST");                     
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);     
             conn.setRequestProperty("file", fileName);                     
             conn.setRequestProperty("user", user_id));

             dos = new DataOutputStream(conn.getOutputStream());          
             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);                    
             dos.writeBytes(lineEnd);      

             // create a buffer of  maximum size
             bytesAvailable = fileInputStream.available();           
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];         
             // read file and write it into form...
             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);
                    Log.i("joshtag","->");
                    }

             // send multipart form data necesssary after file data...
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

             // Responses from the server (code and message)
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage().toString();              
             Log.i("joshtag", "HTTP Response is : "  + serverResponseMessage + ": " + serverResponseCode);  

             // ------------------ read the SERVER RESPONSE
             DataInputStream inStream;
             try {
                 inStream = new DataInputStream(conn.getInputStream());
                 String str;
                 while ((str = inStream.readLine()) != null) {
                     Log.e("joshtag", "SOF Server Response" + str);
                    }
                 inStream.close();
                }
             catch (IOException ioex) {
                Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
                }

             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();    

             if(serverResponseCode == 200){ 
                //Do something                       
                }//END IF Response code 200  

            dialog.dismiss();
            }//END TRY - FILE READ      
        catch (MalformedURLException ex) {
            ex.printStackTrace();     
            Log.e("joshtag", "UL error: " + ex.getMessage(), ex);  
            } //CATCH - URL Exception

         catch (Exception e) {           
            e.printStackTrace();             
            Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
            } //

        return serverResponseCode; //after try       
        }//END ELSE, if file exists.
    }

搜索了大量资源后,我什么也没有得到,但当我试图从$\u服务器超级全局变量获取文本数据时,我获得了所有文本数据和$\u文件以获取图像。

以下是android和php端的代码
package com.example.kingmash.Helper;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.os.StrictMode;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.view;
导入android.widget.ProgressBar;
导入com.example.kingmash.DAO.Profile\u封面;
导入com.example.kingmash.DAO.User\u profile\u cover;
导入com.example.kingmash.main活动;
导入com.example.kingmesh.R;
导入java.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.HashMap;
导入静态com.example.kingmash.Helper.AllRequest.responseMessage;
公共类UploadFileOnlyAsync扩展异步任务{
字符串sourceFileUri,serverResponseMessage;
int服务器响应代码;
ProgressBar ProgressBar;
用户配置文件覆盖upc;
插入int ISDATA;
语境;
public UploadFileOnlyAsync(上下文上下文、字符串sourceFileUri、布尔requireprgressbar、用户\u配置文件\u覆盖upc){
this.sourceFileUri=sourceFileUri;
this.context=上下文;
progressBar=null;
this.upc=upc;
如果(requireprgressbar){
//progressBar=((AppCompatActivity)context.findViewById(R.id.progressBar);
}
}
@凌驾
受保护的void onPreExecute(){
Log.d(“在预----”,“在预----”;
if(progressBar!=null){
progressBar.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
@凌驾
受保护的void onProgressUpdate(void…值){
Log.d(“更新时-----------------”,“”+值[0]);
if(progressBar!=null){
progressBar.setProgress(Integer.parseInt(值[0].toString());
}
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
responseMessage=新配置文件\封面(上下文)。插入(upc,Routes.insertStepsURL);
if(responseMessage.get(0).equals(“插入”)){
Log.d(“键------插入fata”,“插入ISDATA”);
试一试{
HttpURLConnection conn=null;
DataOutputStream dos=null;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
File sourceFile=新文件(sourceFileUri);
if(sourceFile.isFile()){
试一试{
字符串upLoadServerUri=Routes.update\u prfile\u coverr\u URL;
//打开到Servlet的URL连接
FileInputStream FileInputStream=新的FileInputStream(sourceFile);
URL URL=新URL(upLoadServerUri);
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
//打开到URL的HTTP连接
conn=(HttpURLConnection)url.openConnection();
conn.setDoInput(true);//允许输入
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不要使用缓存副本
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“ENCTYPE”,
“多部分/表格数据”);
conn.setRequestProperty(“内容类型”,
“多部分/表单数据;边界=”+边界);
conn.setRequestProperty(“用户id”,“1”);
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”配置文件\“文件名=\”
+sourceFileUri+“\”+lineEnd);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
//读取文件并将其写入表单。。。
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
缓冲区大小=数学
.min(字节可用,最大缓冲区大小);
bytesRead=fileInputStream.read(缓冲区,0,
缓冲区大小);
}
//发送多路径
package com.example.kingmash.Helper;


import android.content.Context;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.example.kingmash.DAO.Profile_cover;
import com.example.kingmash.DAO.User_profile_cover;
import com.example.kingmash.MainActivity;
import com.example.kingmesh.R;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import static com.example.kingmash.Helper.AllRequest.responseMessage;

public class UploadFileOnlyAsync extends AsyncTask<String, Void, String> {
    String sourceFileUri, serverResponseMessage;
    int serverResponseCode;
    ProgressBar progressBar;
    User_profile_cover upc;
    int isdatainserted;
    Context context;

    public UploadFileOnlyAsync(Context context, String sourceFileUri, boolean requireprgressbar, User_profile_cover upc) {
        this.sourceFileUri = sourceFileUri;
        this.context = context;
        progressBar = null;
        this.upc = upc;
        if (requireprgressbar) {
//            progressBar = ((AppCompatActivity) context).findViewById(R.id.progressbar);
        }

    }

    @Override
    protected void onPreExecute() {
        Log.d("on pre----", "on pre-----------");
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
        }


    }

    @Override
    protected void onProgressUpdate(Void... values) {

        Log.d("On update-------------", "" + values[0]);

        if (progressBar != null) {
            progressBar.setProgress(Integer.parseInt(values[0].toString()));
        }

    }

    @Override
    protected String doInBackground(String... params) {
        responseMessage = new Profile_cover(context).insert(upc, Routes.insertStepsURL);
        if (responseMessage.get(0).equals("Inserted")) {
            Log.d("key------insert fata", "" + isdatainserted);
            try {
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(sourceFileUri);
                if (sourceFile.isFile()) {
                    try {
                        String upLoadServerUri = Routes.update_prfile_covrer_URL;
                        // open a URL connection to the Servlet
                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
                        URL url = new URL(upLoadServerUri);
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                        // Open a HTTP connection to the URL
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput(true); // Allow Inputs
                        conn.setDoOutput(true); // Allow Outputs
                        conn.setUseCaches(false); // Don't use a Cached Copy
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("ENCTYPE",
                                "multipart/form-data");
                        conn.setRequestProperty("Content-Type",
                                "multipart/form-data;boundary=" + boundary);
                        conn.setRequestProperty("user_id", "1");
                        dos = new DataOutputStream(conn.getOutputStream());

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

                        dos.writeBytes(lineEnd);

                        // create a buffer of maximum size
                        bytesAvailable = fileInputStream.available();

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

                        // read file and write it into form...
                        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);

                        }

                        // send multipart form data necesssary after file
                        // data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens
                                + lineEnd);

                        // Responses from the server (code and message)
                        serverResponseCode = conn.getResponseCode();
                        serverResponseMessage = conn
                                .getResponseMessage();

                        if (serverResponseCode == 200) {

                            // messageText.setText(msg);
                            //Toast.makeText(ctx, "File Upload Complete.",
                            //      Toast.LENGTH_SHORT).show();

                            // recursiveDelete(mDirectory1);

                        }
                        // close the streams //
                        fileInputStream.close();
                        dos.flush();
                        dos.close();

                        String line;
                        ArrayList responseMessage = new ArrayList();
                        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            Log.d("line---", line);
                            responseMessage.add(line);
                        }

                    } catch (Exception e) {

                        // dialog.dismiss();
                        e.printStackTrace();

                    }
                    // dialog.dismiss();

                } // End else block


            } catch (Exception ex) {
                // dialog.dismiss();

                ex.printStackTrace();
            }
        }
        Log.d("do in back-------------", "" + "Executed " + serverResponseMessage + "" + serverResponseCode + responseMessage);

        return "Executed " + serverResponseMessage + "" + serverResponseCode + "  " + responseMessage;
    }

    @Override
    protected void onPostExecute(String result) {
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }
    }


}
<?php
session_start();
include '../Config/ConnectionObjectOriented.php';
include '../Config/DB.php';
$db = new DB($conn);
$user_id=$_SERVER["user_id"];
$info=$db->fileUploadWithTable($_FILES,"user_profile_cover",$user_id,"../img/user", "5m", "jpg,png");
echo $info[0];
echo $info[1];

// or you can check the detail by this code

foreach (getallheaders() as $name => $value) { 
    echo "$name: $value <br>"; 
}