我正在尝试使用openurlconnection上传图片,但我遇到了一些问题。这是我的java类:
public class Upload extends AppCompatActivity
{
InputStream inputStream;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
StrictMode.enableDefaults();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sss);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String encodedImage = Base64.encodeToString(byte_arr, Base64.DEFAULT);
String msj = downloadImage(encodedImage);
Toast.makeText(getBaseContext(), "mensaje "+msj, Toast.LENGTH_SHORT).show();
}
public String downloadImage(String tabla)
{
String urlG = "http://192.168.43.98/jober/";
try {
URL url = new URL(urlG+"upload.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// para activar el metodo post
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes("image="+tabla);
wr.flush();
wr.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch(Exception e){ return "error";}
}
}
和php代码是:
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.png', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
唯一的问题是当我检查文件时看起来像:
我正在寻找错误,但我无法做到。
答案 0 :(得分:1)
在将字符串发送到PHP之前,必须对字符串进行URLEncode,因为默认的base64解码还包括符号+和=。 变化
String encodedImage = URLEncoder.encode(Base64.encodeToString(byte_arr, Base64.DEFAULT), "UTF-8");
到
req.file('file').upload({
maxBytes: 2000000,
dirname: 'uploadFolder'
}, function (err, files) {
if (err) {
return res.serverError(err);
}
return res.ok();
}
你很高兴。