2017-01-02 68 views
0

我想上傳圖像並將其保存到特定文件夾。這是我的控制器:上傳的圖像沒有存儲在春天的目錄中

@RequestMapping(value = "/echofile",method = RequestMethod.POST) 
     public @ResponseBody HashMap<String, Object> echoFile(HttpServletRequest request, HttpSession session, 
       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 = ((MultipartRequest) request).getFile("file"); 

       MultipartFile file = upldfile.getFile(); 
       String fileName = file.getOriginalFilename(); 

       System.out.println("filename:"+fileName); 
       upldfile.setFile(file); 
       String fileName2 = multipartFile.getOriginalFilename(); 
       System.out.println("filename2:"+fileName2); 

       Long size = multipartFile.getSize(); 
       String contentType = multipartFile.getContentType(); 
       InputStream stream = multipartFile.getInputStream(); 
       byte[] bytes = IOUtils.toByteArray(stream); 


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

       try { 
         // inputStream = ((MultipartFile) upldfile).getInputStream(); 

        inputStream = file.getInputStream(); 
         String webRootDir = session.getServletContext().getRealPath("/"); 
         String url = "E:/Java_Project/EmployeeOnlineRegistrationForm/src/main/webapp/resources/image"; 

         String pathFl = url + File.separator ; 
         File newFile = new File(webRootDir+pathFl+fileName); 
         if (!newFile.exists()) { 
         newFile.createNewFile(); 
         } 
         outputStream = new FileOutputStream(newFile); 
         int read = 0; 
         // byte[] bytes = new byte[1024]; 

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


      } 

     return map; 
    } 

This is my JS ajax part: 

var isJpg = function(name) { 
    return name.match(/jpg$/i) 
}; 

    var isPng = function(name) { 
     return name.match(/png$/i) 
    }; 

    $(document).ready(function() { 
     var file = $('[name="file"]'); 
     var imgContainer = $('#imgContainer'); 

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

     $('#btnSubmit').click(function() { 
      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/EmployeeOnlineRegistrationForm/echofile", 
       type: "POST", 
       //data: formData, 
       data: new FormData(document.getElementById("fileForm")), 
       enctype: 'multipart/form-data', 
       processData: false, 
       modelAttribute:'uploadedFile', 
       contentType: false, 
       success: function(data){ 
        imgContainer.html(''); 
        //var obj = JSON.parse(response); 
        var img = '<img src="data:' + data.contenttype + ';base64,' 
        + data.base64 + '"/>'; 

        alert("success"); 
        imgContainer.append(img); 
       }, 

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

,但是當我輸入的圖像,阿賈克斯提醒我成功,但圖像沒有在div所示,也是我給保存該文件夾(具體目錄)的圖像的路徑,但圖像不保存在該文件夾中。我該做什麼?

Inspects shows the error

+0

你不應該存儲你的web應用程序裏面上傳的文件,巨大的變化在用戶下一次部署這些文件都沒有了。接下來,用作url的字符串也是錯誤的。在部署時沒有'src/main /'等等。所以不知道你構建的是什麼樣的路徑,但看起來不是有用的。 –

回答

0
var byteCharacters = atob(imageData.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')); 
          var byteNumbers = new Array(byteCharacters.length); 
          for (var i = 0; i < byteCharacters.length; i++) { 
           byteNumbers[i] = byteCharacters 
             .charCodeAt(i); 
          } 
          var byteArray = new Uint8Array(byteNumbers); 
          var blob = new Blob([ byteArray ], { 
           type : undefined 

    @RequestMapping(value = "shippingcustomer/{id}/uploadpancard", method =    RequestMethod.POST, 
     consumes = MediaType.MULTIPART_FORM_DATA_VALUE) 
public ResponseEntity<ServiceStatus> UploadPanCard(@PathVariable("id") Long scId, 
     MultipartHttpServletRequest request, HttpServletResponse response, 
     HttpSession session) { 
    try { 
     shippingCustomerService.uploadPancard(scId, request); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    return new ResponseEntity<ServiceStatus> (ServiceStatus.PAN_CARD_UPLOADED, 
      HttpStatus.ACCEPTED); 
} 

@Override 
public void uploadPancard(Long scId, MultipartHttpServletRequest request) { 
    try { 
     ShippingCustomer sc = findShippingCustomer(scId); 
     if (sc != null) { 
      Iterator<String> itr = request.getFileNames(); 
      if (itr.hasNext()) { 
       List<ImageInfo> imgs = ImageInfo 
         .findImageInfoesByImageTypeAndEntityIdEqualsAndImageInfoType(
           DocumentType.PANCARD, scId, ImageInfoType.SC) 
         .getResultList(); 
       for (ImageInfo imageInfo : imgs) { 
        imageInfo.remove(); 
       } 
       MultipartFile file = request.getFile(itr.next()); 
       ImageInfo img = new ImageInfo(); 
       img.setImage(file.getBytes()); 
       img.setEntityId(scId); 
       img.setImageInfoType(ImageInfoType.SC); 
       img.setImageType(DocumentType.PANCARD); 
       img.persist(); 
      } 
     } else { 
      throw new ShippingCustomerNotFoundException(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

請考慮添加一些文字來解釋您的答案。謝謝。 –

相關問題