private void doFileUpload(){
File file1 = new File(selectedPath1);
String urlString = "http://example.com/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}这段代码是我从互联网上得到的。这是工作,但当我尝试上传大于1兆字节文件时,
我遇到了一个文件大小错误。
我知道如何调整位图图像的大小,但我不知道如何上传调整大小的位图图像。
如何使用filebody调整大小和上传?
提前感谢
发布于 2013-03-21 05:57:27
您不仅需要调整位图的大小,还需要将结果编码为.jpg图像。因此,必须打开文件并将其转换为位图,将位图调整为较小的图像,将图像编码为byte[]数组,然后以与上载文件file1相同的方式上载byte[]数组。
如果位图很大,那么您将没有足够的堆内存来打开整个位图,因此您必须使用BitmapFactory.Options.inSampleSize打开它。
首先,打开缩小大小的位图:
Uri uri = getImageUri(selectedPath1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Example, there are also ways to calculate an optimal value.
InputStream in = in = contentResolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);接下来,编码成一个byte[]数组:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bitmapdata = bos.toByteArray();最后,使用reqEntity.addPart()直接添加byte[]数组,或者写入一个较小的文件并添加该文件,如当前示例所示。
发布于 2015-01-13 05:25:47
这个答案是is based on another answer,但我对该代码有一些问题,所以我发布了经过编辑和工作的代码。
我是这样做的:
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth = 50; //pixels
options.outHeight = 50; //pixels
InputStream in = context.getContentResolver().openInputStream(data.getData()); // here, you need to get your context.
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bitmapdata = baos.toByteArray();请注意,data是从用于获取文件的意图返回的数据。如果您已经有了文件路径,只需使用该路径...
现在,在创建HTTP实体时,添加:
FormBodyPart fbp = new FormBodyPart("image", new ByteArrayBody(baos.toByteArray(), "image/jpeg", "image"));
entity.addPart(fbp);另外,请注意您需要一个MultipartEntity来上传文件。
https://stackoverflow.com/questions/15534980
复制相似问题