base64到图像文件

时间:2014-01-10 09:20:08

标签: java jquery html5 filereader

我正在使用summernote并希望异步地获得服务器上传功能。我打算将图像转换为base64并通过ajax发送到servlet,我将保存压缩文件并将图像文件的url返回到编辑器src,如下所示:

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代码。在这里我得到文件为null。我相信我应该在这里获取文件字符串。有人可以帮忙吗?

 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);


    }

3 个答案:

答案 0 :(得分:1)

我终于找到了这个问题的答案。 我必须在表单中修改summernote和包装文件输入,并从那里使用iframe返回表单。

我用google搜索,发现由于安全原因,我们无法动态地将文件名设置为文件输入。

答案 1 :(得分:0)

你能试试request.getReader()吗?

答案 2 :(得分: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();
}