Spring MVC with ajax file upload and MultipartFile

后端 未结 5 1156
余生分开走
余生分开走 2021-01-06 13:15

I have an issue using Ajax upload with Spring 3 MVC. I understand that I have to configure multipartResolver bean in spring config, which I\'ve done. Than I can have control

5条回答
  •  无人及你
    2021-01-06 13:26

    my solution:

    @RequestMapping(value = "/create/upload", method = RequestMethod.POST, consumes="multipart/form-data", produces="application/json")
    @ResponseBody()
    public String handleImageUpload(@RequestParam(value="qqfile", required=true) MultipartFile[] files, 
            @ModelAttribute(value="files") List filesSession) throws IOException, FileUploadException {
    
        if (files.length > 0) {
            filesSession.addAll(Arrays.asList(files));
            // store the bytes somewhere
            return  "{\"success\": true}";
        }
        else {
            return "{\"success\": false}";
        }
    }
    
    @RequestMapping(value = "/create/upload", method = RequestMethod.POST, consumes="application/octet-stream", produces="application/json")
    @ResponseBody()
    public String handleImageUploadApplication(HttpServletRequest request, 
            @ModelAttribute(value="files") List filesSession) throws IOException, FileUploadException {
    
        if (request.getInputStream() != null) {
            // creamos el fichero temporal
            File file = File.createTempFile("file", "valumns",
                    RepositoryData.getRepositoryData());
            FileOutputStream fos = new FileOutputStream(file);
            // copiamos contenido
            Streams.copy(request.getInputStream(), fos, true);
            //TODO: 
            //filesSession.addAll(Arrays.asList(files));
            // store the bytes somewhere
            return  "{\"success\": true}";
        }
        else {
            return  "{\"success\": true}";
        }
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
    public void handleException(Exception ex) {
        log.error("Ocurrio un error en el album", ex);
    }
    

提交回复
热议问题