使用以下代码将图像上传到服务器 -
final InputStream fileInputStream = MyApplication.getInstance().getContentResolver().openInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fileInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
final byte[] bitmapData = byteArrayOutputStream.toByteArray();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
if (bitmap != null) {
ContentType contentType = ContentType.create("image/png");
builder.addBinaryBody("", bitmapData, contentType, "");
final HttpEntity httpEntity = builder.build();
StringRequest request =
new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
};
上传图片没问题,但在文件中添加正文标题有问题
--0Iw7PkPg_BhQghFGBR1_lBhO1RaCaBsZJ-U
Content-Disposition: form-data; name=""; filename=""
Content-Type: image/png
âPNG
....
--0Iw7PkPg_BhQghFGBR1_lBhO1RaCaBsZJ-U--
如果我从文件中删除特定内容,则可以轻松将该图像用作PNG。是否有一种方法只上传PNG文件部分到服务器?