来自andriod我正在尝试上传图片,我正在使用java中的Web服务

时间:2018-02-13 14:21:24

标签: spring spring-mvc multipartform-data

下面是android部分

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

下面是我在web服务中的java控制器

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

    } 

输出是我在控制台中获得的但是文件被创建但是它已损坏且大小为0bytes,

  

--------- AndroidUploadService1518510071115 Content-Disposition:form-data; NAME = “图像”;文件名= “IMG_20180211_000033.jpg”   内容类型:image / jpeg

     

ÿØÿá3ØExif

我试着将它放在java控制器中,但它无法正常工作

  

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

但我只想在春天MVC做,帮我上传文件

1 个答案:

答案 0 :(得分:0)

这是一个工作文件上传器

    @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注册为拒绝。

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

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

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

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

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