2014-01-10 119 views
0

我使用summernote並希望異步服務器上傳能力。我打算圖像轉換爲Base64和發送通過Ajax與Servlet在那裏,我會保存壓縮文件並返回圖像文件的URL爲下面編輯器源:下面base64到圖像文件

var edit = function() { 
    $('.click2edit').summernote({ 
     focus: true, 
     onImageUpload: function(files, editor, welEditable) { 
      sendFile(files[0],editor,welEditable); 
     } 
     }); 
}; 
function sendFile(file,editor,welEditable) { 

    alert(file.size); 
    var reader = new FileReader(); 
    var imgfile = reader.readAsBinaryString(file); 
    alert(file); 
    $.ajax({ 
      method:"POST", 
      url: 'imageupload', 
      data: {imageFile:imgfile}, 
      success:function(response) 
      { 
       alert("file uploaded successfully"); 
       return response; 
       }, 
      error: function(response,status,err) 
      { 
       alert("upload failed"); 
      } 
     }); 
} 

是我的servlet代碼。在這裏我得到的文件爲空。我相信我應該把文件作爲字符串在這裏。有人可以幫忙嗎?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     System.out.println("image upload"); 
     String file = (String)request.getParameter("imageFile"); 
     System.out.println("file: " + file); 
     PrintWriter out = response.getWriter(); 
     response.setContentType("text/html"); 
     out.print(file); 


    } 

回答

0

你可以試試request.getReader()

0

試試這個

public static BufferedImage decodeToImage(String imageString) 
{ 
    BufferedImage image = null; 
    byte[] imageByte; 
    try 
    { 
     BASE64Decoder decoder = new BASE64Decoder(); 
     imageByte = decoder.decodeBuffer(imageString); 
     ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); 
     image = ImageIO.read(bis); 
     bis.close(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return image; 
} 

public static String encodeToString(BufferedImage image, String type) 
{ 
    String imageString = null; 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    try 
    { 
     ImageIO.write(image, type, bos); 
     byte[] imageBytes = bos.toByteArray(); 

     BASE64Encoder encoder = new BASE64Encoder(); 
     imageString = encoder.encode(imageBytes); 

     bos.close(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    return imageString; 
} 

如果妳從URL

try 
{ 
    URL url = new URL("example.com/example.txt"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
    String str; 
    while ((str = in.readLine()) != null) 
    { 
     // str is one line of text; readLine() strips the newline character(s) 
    } 
    in.close(); 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
1

我終於找到這個問題的答案閱讀文件。 我不得不修改formnote中的summernote和包裹文件輸入,並從那裏返回了我使用iframe發佈的表單。

我使用Google搜索,發現由於安全原因,我們無法動態地將文件名設置爲文件輸入。