我有一份登记表。除了名字,姓氏和用户名等用户信息外,我希望用户上传图片。
目前,我已设法使用相机在ImageView中加载图像缩略图并显示在视图中。现在我也想上传图片。
以下是我Register.java
中的代码,只有字符串才能正常运行。
String requested_method = "register";
RegisterTask registerTask = new RegisterTask(Register.this);
registerTask.execute(requested_method, first_name_entered, last_name_entered, username_entered);
由于我的RegisterTask.java
是一个大文件,因此我只是在这里粘贴相关信息。
public class RegisterTask extends AsyncTask<String,Void,String> {
Context context;
public RegisterTask(Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String register_url = "http://my_website.com/register.php";
String requested_method = params[0];
String first_name = params[1];
String last_name = params[2];
String username = params[3];
if (requested_method.equals("register")) {
try {
URL url = new URL(submit_order_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("first_name","UTF-8")+"="+URLEncoder.encode(first_name,"UTF-8")+"&"
+URLEncoder.encode("last_name","UTF-8")+"="+URLEncoder.encode(last_name,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response_data = "";
String line = "";
while((line = bufferedReader.readLine()) != null) {
response_data+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response_data;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
此代码工作正常。
现在我想要做的是,将我在ImageView中加载的图像添加到此AsyncTask并上传。如果我尝试将Bitmap与字符串一起发送,则会出错。
我该怎么办?
答案 0 :(得分:0)
使用新类,将其命名为RegistrationDetails
,并使其包含当前字符串以及Bitmap
。只需传递该类的实例作为AsyncTask
的唯一参数。