2017-09-25 44 views
2

的我發送圖像到服務器端的字節數。我收到的圖像形式爲第三方爲base64格式,爲了減少傳輸帶寬,我將這些數據作爲二進制發送(必須進行解碼)。請注意我只在服務器端需要這個二進制數據。無法接收從阿賈克斯到Java的圖像,但能夠接收圖像

我現在面臨的問題: 考慮一個例子,如果我從JS送5KB文件到Java。我能夠接收並查看保存文件的位置。但該文件似乎已損壞,無法在ms paint或任何其他圖像應用程序中打開。 我能夠在java調試器中看到表單(圖像)項目的字節數! 我已經嘗試了很多下面的代碼,我無法找到真正的問題是什麼?

JSP代碼:

function oneMore(){ 
var base64ImageData = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wCEAA0JCgsKCA" 
var converted = Base64.decode(base64ImageData); 
//(this is just an sample) 
    var formdata = new FormData(); 
     formdata.append("image", converted); 

     /* var formdata = new FormData(); 
     formdata.append("image", image); */ 
     $.ajax({ 
      url : '/RegisterServlet_2/servlet/Register', 
      type : "POST", 
      data : formdata, 
      enctype : 'multipart/form-data', 
      processData : false, 
      contentType : false 
     }).done(function(data) 
     { 
      alert('File upload completed ...'); 
     }).fail(function(jqXHR, textStatus) 
     { 
      alert('File upload failed ...'); 
     }); 
    } 
</script> 

</head> 
<body > 
    <input type="button" id="testId" name="testName" value="Tester" onclick="oneMore();"> 
</body> 

Java方面:

import java.awt.Image; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.List; 

import javax.imageio.ImageIO; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 

public class Register extends HttpServlet 
{ 
    private static final long serialVersionUID = -4562252992447370243L; 

    // location to store file uploaded 
    private static final String UPLOAD_DIRECTORY = "D:/"; 

    // upload settings 
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB 
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB 
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB 

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    { 
     // checks if the request actually contains upload file 
     if (!ServletFileUpload.isMultipartContent(request)) 
      return; 

     // configures upload settings 
     DiskFileItemFactory factory = new DiskFileItemFactory(); 
     // sets memory threshold - beyond which files are stored in disk 
     factory.setSizeThreshold(MEMORY_THRESHOLD); 
     // sets temporary location to store files 
     factory.setRepository(new File(System.getProperty("catalina.base"), "temp")); 
     System.out.println(factory.getRepository()); 

     ServletFileUpload upload = new ServletFileUpload(factory); 

     // sets maximum size of upload file 
     upload.setFileSizeMax(MAX_FILE_SIZE); 

     // sets maximum size of request (include file + form data) 
     upload.setSizeMax(MAX_REQUEST_SIZE); 

     // constructs the directory path to store upload file 
     // this path is relative to application's directory 
     String uploadPath = UPLOAD_DIRECTORY; 

     try 
     { 
      // parses the request's content to extract file data 
      @SuppressWarnings("unchecked") 
      List<FileItem> formItems = upload.parseRequest(request); 

      if (formItems != null && formItems.size() > 0) 
      { 
       // iterates over form's fields 
       for (FileItem item : formItems) 
       { 
        if(item==null) 
         continue; 

        String filePath = uploadPath + File.separator + "Image" + System.currentTimeMillis() + ".jpg"; 
        File storeFile = new File(filePath); 
        System.out.println(storeFile); 

        // saves the file on disk 
        item.write(storeFile); 

        InputStream is = item.getInputStream(); 
        BufferedImage image = ImageIO.read(is); 

        ImageIO.write(image, "jpg", storeFile); 



       } 
      } 
     } catch (Exception ex) 
     { 
      ex.printStackTrace(); 
     } 
    } 
} 

我是缺少在這裏? 在此先感謝!

回答

0

我可以能夠通過傳輸圖像只需按照與BLOB轉換在Java腳本變化:

function oneMore() 

{ 
    var base64ImageData = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wCEAA0JCgs" 
    var formData = reduceImgTransferBandwidth(base64ImageData); 

    // debugger; 
    $.ajax({ 
     url : '/RegisterServlet_2/servlet/Register', 
     type : "POST", 
     data : formData, 
      enctype: 'multipart/form-data', 
     processData : false, 
     contentType : false 
    }).done(function(data) 
    { 
     //alert('File upload completed ...'); 
    }).fail(function(jqXHR, textStatus) 
    { 
     //alert('File upload failed ...'); 
    }); 
} 



    function reduceImgTransferBandwidth(pimagedata) 
    { 
     var form = document.createElement("myForm"); 
     var ImageURL = "data:image/gif;base64," + pimagedata; 
     var block = ImageURL.split(";"); 
     var contentType = block[0].split(":")[1]; 
     var realData = block[1].split(",")[1]; 
     var blob = b64toBlob(realData, contentType); 
     var formDataToUpload = new FormData(form); 

     formDataToUpload.append("image", blob); 

     return formDataToUpload; 

    } 

    function b64toBlob(b64Data, contentType, sliceSize) 
    { 
     contentType = contentType || ''; 
     sliceSize = sliceSize || 512; 

     var byteCharacters = atob(b64Data); 
     var byteArrays = []; 

     for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) 
     { 
      var slice = byteCharacters.slice(offset, offset + sliceSize); 

      var byteNumbers = new Array(slice.length); 
      for (var i = 0; i < slice.length; i++) 
      { 
       byteNumbers[i] = slice.charCodeAt(i); 
      } 

      var byteArray = new Uint8Array(byteNumbers); 

      byteArrays.push(byteArray); 
     } 

     var blob = new Blob(byteArrays, { 
      type : contentType 
     }); 
     return blob; 
    }