from andriod i am trying to upload image and i am using web services in java

below is the android part

new MultipartUploadRequest(this,uploadid,UPLOAD_URL)
                .addFileToUpload(path,"image")
                .addParameter("name",name)
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload();

below is my java controller in web services

@RequestMapping(value = "/uploadm",method=RequestMethod.POST)
public void submitQuestionuploading(@RequestBody String image) throws Exception 
{   
    System.out.println(1+""+image);



        try {


             byte[] bytes = image.getBytes();
             System.out.println(11);
             BufferedOutputStream stream =new BufferedOutputStream(new 
             FileOutputStream(new File(UPLOAD_DIRECTORY +"11.png")));  
             stream.write(bytes);  
             stream.flush();  
             stream.close();
          } 
              catch (Exception e) {
            System.out.println(e);

    } 

output is this one i got in console but file is created but it is corrupted and it s size 0bytes ,

---------AndroidUploadService1518510071115 Content-Disposition: form-data; name="image"; filename="IMG_20180211_000033.jpg" Content-Type: image/jpeg

ÿØÿá3ØExif

i tried to put this in java controller but it is not working

@RequestMapping(value = "/upload", method = RequestMethod.POST , headers = "Content-Type=multipart/form-data") public String fileUpload(@RequestParam("image") CommonsMultipartFile file) {}

but i want to do in spring MVC only, help me to take uploaded file


This is a working file uploader

    @ResponseStatus(code = HttpStatus.CREATED)
@RequestMapping(value = "asset", method = RequestMethod.POST, consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String uploadImage(
        @RequestParam("image") MultipartFile file) {
    byte[] bytes = file.getBytes();
    //do something with byte

    return "ok or anything you want to return";
}

And also you need to register MultipartResolver as a depandency.

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);
    return multipartResolver;
}

you can deploy this code and then test using postman.

there are various tutorials for this. you may have a look at

http://www.baeldung.com/spring-file-upload

https://www.boraji.com/spring-4-mvc-file-upload-example-with-commons-fileupload

链接地址: http://www.djcxy.com/p/8580.html

上一篇: 为什么使用PUT DELETE POST GET?

下一篇: 从andriod我想上传图片,我正在使用Java中的Web服务