0

我正在将图像从我的 Android 应用程序上传到我的服务器。

在手机中我的图片大小是 1.5MB 上传后图片的大小是 250KB

图像宽度和高度没有改变

    AsyncHttpClient client = new AsyncHttpClient();
    File myFile = new File(imagePath);
    RequestParams params = new RequestParams();
    try {
        params.put("img", myFile);
        params.put("key1", request.getText().toString());
    } catch(FileNotFoundException e) {
        Log.d("MyApp", "File not found!!!" + imagePath);
    }
    client.post(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            answer.setText(response);
        }

        @Override
        public void onStart() {
        super.onStart();
        }

        @Override
        public void onFailure(Throwable arg0, String arg1) {
        super.onFailure(arg0, arg1);
        Log.d("MyApp", arg0.getMessage().toString());
        }

    });

在服务器中,我使用以下 servlet 代码获取图像:

    Part part = request.getPart("key1");
    Part img = request.getPart("img");
    if (part!=null && img!=null){
        String name = getValue(part);
        InputStream is = img.getInputStream();
        BufferedImage bufImage = ImageIO.read(is); 
        ImageIO.write(bufImage, "jpg", new File("c:/file_"+name+".jpg"));
        out.println(name + " I got your image ");
    } else {
        out.println("image upload failed");
    }
    out.flush();
    out.close();

谢谢

4

1 回答 1

0

我找到了解决方案,问题出在servlet中,下面是解决方案

Part fName = request.getPart("name");
Part img = request.getPart("img");
if (fName!=null && img!=null){
    String name = getValue(fName);
    InputStream is = img.getInputStream();
    OutputStream o = new FileOutputStream("c:/file_"+name+".jpg"); 
    copy(is, o); //The function is below 
    o.flush(); 
    o.close(); 
    out.println(name + " I got your image ");
} else {
    out.println("image upload failed");
}
out.flush();
out.close();

public static long copy(InputStream input, OutputStream output) throws IOException { 
    byte[] buffer = new byte[4096]; 

    long count = 0L; 
    int n = 0; 

    while (-1 != (n = input.read(buffer))) { 
        output.write(buffer, 0, n); 
        count += n; 
    } 
    return count; 
} 
于 2012-09-20T07:58:18.963 回答