0

我编写了这个AsyncTask类,它可以毫无问题地将一组 POST 数据发送到我的 php 服务器。现在我想扩展它,以便它也将文件发送到同一个脚本(我已经在 php 文件中进行了接收处理​​)。我的意思是我希望它一次性发布 DATA + FILE。像多部分实体或从 HTML 动作到 php 脚本的东西。

我需要在这个类中添加什么以便它可以上传包含其他内容的文件?

public class UpdateSnakeGameStatusTask extends AsyncTask<String, Integer, HttpResponse> {
    private Context mContext;
    private ArrayList<NameValuePair> mPairs;

    /**
     * @param context The context that uses this AsyncTask thread
     * @param postPairs <b>NameValuePair</b> which contains name and post data
     */
    public UpdateSnakeGameStatusTask(Context context, ArrayList<NameValuePair> postPairs) {
        mContext = context;
        mPairs = new ArrayList<NameValuePair>(postPairs);
    }

    @Override
    protected HttpResponse doInBackground(String... params) {
        HttpResponse response = null;
        HttpPost httppost = new HttpPost(params[0]); //this is the URL

        try {
            httppost.setEntity(new UrlEncodedFormEntity(mPairs));
            HttpClient client = new DefaultHttpClient();
            response = client.execute(httppost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
4

1 回答 1

0

好的,正如@greenapps 建议的那样(归功于他)我这样解决了。

还没有完全解决,因为我必须在服务器端解码文件内容并将其手动保存在服务器上。

所以我将文件内容添加到BasicNameValuePair我已经拥有的文件中:

String fileAsBase64 = Base64.encodeToString( convertToByteArray(mFile)
                , Base64.DEFAULT);

    mPostPairs.add(new BasicNameValuePair("filecontent", fileAsBase64));

这是将其转换为字节数组的方法:

/**
 *  Reads a file and returns its content as byte array
 * @param file file that should be returned as byte array
 * @return byte[] array of bytes of the file
 */
public static byte[] convertTextFileToByteArray(File file) {
    FileInputStream fileInputStream = null;
    byte[] bFile = new byte[(int) file.length()];
    try {
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
    }catch(Exception e){
        e.printStackTrace();
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fileInputStream = null;
        }
    }
    return bFile;
}

在服务器端,我这样做:

$content = imap_base64 ($_POST["filecontent"]);

负责将内容解码恢复正常。

希望这对其他人也有帮助

于 2014-04-30T00:55:55.320 回答