nmkkannan
nmkkannan

Reputation: 1303

Spring with android image uploading

I want to upload image from android to server. My android asyc code :

    final String jsonUserMo = gson.toJson(userMO);
    final StringBuilder contactLists = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("userMO", jsonUserMo));
        HttpPost post = new HttpPost(Constants.ROOTURL+"/media/uploadUserImage");
        post.setEntity(new FileEntity(new File()));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        contactLists.append(rd.readLine());
    } catch (Exception e) {
        e.printStackTrace();
    }

My controller code :

@RequestMapping(value = { "/uploadUserImage" }, method = RequestMethod.POST)
public @ResponseBody
String uploadUserImage(@RequestParam(value = "uploadImg") MultipartFile file, @RequestParam("userMO") String userBO, HttpSession session, HttpServletRequest httpServletRequest) {
    log.info("hitting image");
    UserBO userBo = gson.fromJson(userBO, UserBO.class);
    // jboss file location to store images
    String filePath = httpServletRequest.getSession().getServletContext().getRealPath("/") + "\\resources\\userImages\\" + userBo.getRingeeUserId() + ".png";
    String fileName = file.getOriginalFilename();
    try {
        if (!file.isEmpty() && file.getBytes().length >= 5242880) {
        log.info("file size is "+file.getBytes());
        }
        if (!file.isEmpty()) {
    //some logic 
        }
    } catch (Exception Exp) {
        log.info("Upload image failure");

    }
    return "";
}

My servlet config:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- <property name="maxUploadSize" value="5242880" /> -->
</bean>

My problem is how to add Bitmap file in httppost to send controller. Link:Unable to add MultipartEntity because its deprecated Otherwise working for passing java object from android to controller. I want upload image file from android [using httppost] to controller. Any mistakes from me.. please help me?

Upvotes: 3

Views: 1054

Answers (2)

Stan
Stan

Reputation: 6561

After all when you do setEntity 2 times in a row doesn't the 2nd one ovewrite/cancel the first set here:?

post.setEntity(new FileEntity(new File()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

And about passing a file: Like I said in comments you should add a path to a file when you pass a new File() inside of a new FileEntity():

post.setEntity(new FileEntity(new File("path_to_a_file")));

If you want to pass a Bitmap from an ImageView there are some options. You caould store the Bitmap into a PNG or JPEG file first and then pass that file:

        final File imageFile = File.createTempFile();// temp file to store Bitmap to
        // Convert bitmap to byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
// here you have a stream - you could try yo upload it if you want to
        // compressing Bitmap to a PNG
        bitmap.compress(CompressFormat.PNG, 100, bos);

        // write the bytes in file
        isSucceed = FileUtils.byteArrayOutputStreamToFile(bos, imageFile);
        // if (isSucceed) your Bitmap is stored into a file successfully
        // closing a stream
        if (bos != null)
            try {
                bos.close();
            } catch (IOException e) {}

Or could try to upload your Bitmap as a stream.
Also you should add a MIME type to a FileEntity constructor (like here):

new FileEntity(new File(),"image/jpeg;");

Also to make a proper MultiPart upload these articles might be helpful:
Upload files by sending multipart request programmatically
and
A good approach to do multipart file upload in Android

Upvotes: 0

Arun
Arun

Reputation: 11

        final File file1 = new File(url_path);

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(http_url_path1);
        FileBody bin1 = new FileBody(file1);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("abc", new StringBody(abcid));
        reqEntity.addPart("xyz", new StringBody(xyzid));
        reqEntity.addPart("file", bin1);
        reqEntity.addPart("key", new StringBody(Key));
        reqEntity.addPart("authentication_token", new StringBody(Authe_Key));
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();

hoping this will work...

Upvotes: 1

Related Questions