弹簧与Android图像上传

时间:2015-04-06 11:29:30

标签: java android spring

我想将图像从android上传到服务器。 我的android asyc代码:

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

我的servlet配置:

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

我的问题是如何在httppost中添加位图文件来发送控制器。 链接:Unable to add MultipartEntity because its deprecated 否则工作将java对象从android传递给控制器​​。 我想从android [使用httppost]上传图像文件到控制器。 我的任何错误.. 请帮帮我?

2 个答案:

答案 0 :(得分: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();
希望这会有效......

答案 1 :(得分:0)

毕竟当你连续2次执行setEntity时,第二个没有写入/取消第一个设置:?

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")));

如果要从ImageView传递位图,则有一些选项。您可以先将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) {}

或者可以尝试将您的位图上传为流 您还应该向FileEntity构造函数(MIME)添加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