【问题标题】:Why uploaded image is not saved in specific folder in spring?为什么春天上传的图片没有保存在特定文件夹中?
【发布时间】:2017-01-01 07:04:32
【问题描述】:

我正在尝试上传特定文件夹中的图像。点击按钮后,ajax返回成功提示,但文件夹中没有保存文件。

这是我的控制器:

 @RequestMapping(value = "/echofile",method = RequestMethod.POST)
    public @ResponseBody HashMap<String, Object> echoFile(HttpServletRequest  request,
            HttpServletResponse response ,  @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
     HashMap<String, Object> map = new HashMap<String, Object>();

     if(request instanceof MultipartHttpServletRequest){

         InputStream inputStream = null;
            OutputStream outputStream = null;
          // MultipartFile multipartFile = request.getFile("file");

            MultipartFile file = upldfile.getFile();
            String fileName = file.getOriginalFilename();
            System.out.println("vcvvvvvvvv"+fileName);
            upldfile.setFile(file);

            Long size = file.getSize();
            String contentType = file.getContentType();

            InputStream stream = file.getInputStream();
            byte[] bytes = IOUtils.toByteArray(stream);


            map.put("fileoriginalsize", size);
            map.put("contenttype", contentType);
            map.put("base64", new String(Base64Utils.encode(bytes)));

            try {


                inputStream = file.getInputStream();

                   File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
                   if (!newFile.exists()) {
                    newFile.createNewFile();
                   }
                   outputStream = new FileOutputStream(newFile);
                   int read = 0;
                  byte[] byt = new byte[1024];

                   while ((read = inputStream.read(byt)) != -1) {
                    outputStream.write(byt, 0, read);
                   }
                  } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                  }


     }
     return map; 


     }

这是我的 ajax 调用:

  function uploadImage() {

            var file = $('[name="file"]');
            //var imgContainer = $('#imgContainer');

            var formData = new FormData();
            formData.append('file', jQuery('input[type=file]')[0].files[0]);
            var filename = $.trim(file.val());

            if (!(isJpg(filename) || isPng(filename))) {
                alert('Please browse a JPG/PNG file to upload ...');
                return;
            }

             $.ajax({
                url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
                type: "POST",
                data: new FormData(document.getElementById("fileForm")), 
                //data: formData,
                enctype: 'multipart/form-data',
                processData: false,
                aync: false,
                modelAttribute:'uploadedFile',
                headers: {'Content-Type': 'multipart/form-data'},
                contentType: false,
             /*  }).done(function(data) {

                 var img = '<img src="data:' + data.contenttype + ';base64,'
                      + data.base64 + '"/>';
                  alert("success");

             }).fail(function(jqXHR, textStatus) {

                  alert('File upload failed ...');
              });  */

            success: function(response){

                var obj = JSON.parse(response);
                alert(response);

            },

            error: function(){                      
                alert('Error while request..');
            }
        });   
        }

当我点击上传按钮时,提示成功部分的作品。 eclipse 和浏览器的控制台都没有显示任何错误。但文件未保存在资源/图像文件夹中。问题出在哪里?

【问题讨论】:

    标签: jquery ajax spring


    【解决方案1】:

    假设您有一个将多部分表单数据提交到 url 的表单。你有一个控制器。

    @RequestMapping(value = "/products/create", method = RequestMethod.POST)
    public String createProject(@ModelAttribute Product product, BindingResult bindingResult,
            @RequestParam("image") MultipartFile multipartFile, Model model) throws IOException {
        if (bindingResult.hasErrors()) {
            System.out.println("BINDING ERROR: " + bindingResult.toString());
        }
        if (productService.isImageValid(multipartFile)) {
            product.setImage(multipartFile.getBytes());
        } else {
            model.addAttribute("message", "Invalid Image!");
        }
    
        productService.saveAndFlush(portfolio);
        model.addAttribute("message", "Successfully saved project!");
    
        return "redirect:/products";
    }
    

    检查图片是否有效:

    public boolean isImageValid(MultipartFile multipartFile){
        try {
            Image image = ImageIO.read(this.convertToFile(multipartFile));
            if (image!=null) {
                return true;
            }
        } catch (IOException e) {
            System.out.println("IOException: "+e.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return false;
    }
    
    
    private File convertToFile(MultipartFile multipartFile) throws Exception{
        File file = new File(multipartFile.getOriginalFilename());
        file.createNewFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(multipartFile.getBytes());
        fileOutputStream.close();
        return file;
    }
    

    您的表单可能如下所示:

    <form th:action="@{/products/create}" enctype="multipart/form-data">
        Name: <input type="text" name="name"></input>
        Product Id: <input type="number" name="id"></input>
        Choose an image: <input type="file" name="image"></input>
    
        <button type="submit">Create</button>
    </form>
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2013-02-14
      • 2018-08-04
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 2018-09-06
      • 2014-02-19
      相关资源
      最近更新 更多