2015-04-06 3 views
3

Я хочу загрузить изображение с android на сервер. Мой андроид код asyc:Spring with android image uploading

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(); 
    } 

Мой код контроллера:

@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 ""; 
} 

Мой сервлет конфигурации:

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

Моя проблема заключается в том, чтобы добавить файл Bitmap в HttpPost отправить контроллер. Ссылка: Unable to add MultipartEntity because its deprecated В противном случае работает для передачи объекта java от android к контроллеру. Я хочу загрузить файл изображения с android [using httppost] на контроллер. Любые ошибки от меня .. , пожалуйста, помогите мне?

+0

post.setEntity (новый FileEntity (новый файл (INSERT_PATH_TO_IMAGE_FILE_HERE)) ;? – Stan

+0

Спасибо @ Stan.Now я попробую – nmkkannan

+0

У меня есть одно сомнение, какие-либо возможности добавления файла растрового изображения в httppost? – nmkkannan

ответ

0

В конце концов, когда вы устанавливаетеEntity 2 раза подряд, не 2-й оберегает/отменяет первый набор здесь :?

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

И о прохождении файла: Как я уже сказал в комментарии, вы должны добавить путь к файлу при передаче new File() внутри new FileEntity():

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

Если вы хотите передать Bitmap из ImageView есть несколько вариантов. Вы caould хранить Bitmap в PNG или JPEG файла, а затем передать этот файл:

 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) {} 

Или может попытаться загрузить Bitmap как поток.
Кроме того, вы должны добавить MIME типа конструктору FileEntity (like here):

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

Кроме того, чтобы сделать правильный MULTIPART загрузить эти статьи могут быть полезны:
Upload files by sending multipart request programmatically
и
A good approach to do multipart file upload in Android

+0

Спасибо @ Stan, Есть ли возможности добавить файл растрового изображения в httppost? – nmkkannan

+0

'new File ("/mnt/photos/my_bitmap.bmp ")', если это действительно битмап-файл - http://en.wikipedia.org/wiki/BMP_file_format или 'new File ("/mnt/photos/my_bitmap. jpg ")', так как вы упомянули файл в любом случае. – Stan

+0

@ Спасибо за помощь .. я проверю его .. – nmkkannan

1
 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(); 

надеясь, что это сработает ...

+0

MultipartEntity устарел или я не получил ресурсы для MultipartEntity – nmkkannan