在我目前的春天的项目,我有一些input[type=file]
场这就需要通过这个PropertyEditorSupport类进行处理的一种形式:转换Base64编码字符串到字节数组
public class ImagemEditor extends PropertyEditorSupport {
private String file_path = System.getProperty("user.home")+File.separator+".store"+File.separator+"Pictures";
@Override
public void setAsText(String text) {
...
}
...
}
图像发送到服务器为Base64字符串并且它是由这段JavaScript代码添加到其他PARAMS:
$('input[type=file]').on("change", function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
if(typeof id !== "undefined") {
if(this.files.length > 0) {
reader = new FileReader();
reader.onloadend = function() {
str += "&" + name + "=" + this.result;
}
reader.readAsDataURL(this.files[0]);
}
}
});
在PropertyEditorSupport类,我看与Base64编码的图像串并转换为byte[]
,只是为了存储这些字节到一个文件:
byte[] buffer = Base64.decodeBase64(text.split(",")[1]);
File arquivo;
try {
arquivo = new File(file_path+File.separator+file_name()+".jpeg");
} catch (Exception e) {
e.printStackTrace();
arquivo = null;
}
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
if(!arquivo.exists())
try {
arquivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream(arquivo);
} catch (Exception e) {
e.printStackTrace();
fileOut = null;
}
try {
fileOut.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}
try {
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
但是当我尝试打开生成的图像,它是不一样的图像我上传(我使用命令行工具vbindiff
验证,并且图像的头始终是相同的)。甚至无法打开生成的图像(我在Linux/Kubuntu上使用Gwenview)。
有人可以看到这里有什么问题吗?
这里的缓冲区ByteArrayInputStream的新(缓冲)相同这里的缓冲区的字节[]缓冲区? – reos
是的,它是相同的变量。 –
嗯我建议你使用编码,基本的东西base64。您在客户端编码图像,然后在解码的服务器中编码。 – reos