关于spring:从android我试图上传图像,我在java中使用Web服务

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

下面是Android部分

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

下面是我在Web服务中的Java控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@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);

    }

输出是我在控制台中得到的,但文件已创建,但它已损坏,大小为0字节,

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

???á3?Exif

我试图把它放到Java控制器中,但是它不工作。

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

但我只想在春季做一件事,帮助我上传文件。


这是一个工作文件上传程序

1
2
3
4
5
6
7
8
9
10
11
    @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";
}

另外,您还需要将multipartresolver注册为depandency。

1
2
3
4
5
6
@Bean(name ="multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);
    return multipartResolver;
}

您可以部署此代码,然后使用postman进行测试。

有各种各样的教程。你可以看看

File Upload with Spring MVC

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