2017-01-01 13 views
1

特定のフォルダに画像をアップロードしようとしています。ボタンをクリックすると、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とブラウザの両方のコンソールにエラーは表示されません。しかし、ファイルはリソース/イメージフォルダに保存されません。問題はどこだ?

答えて

0

複数パートのフォームデータを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> 
関連する問題