In my current spring project, I have a form with some input[type=file]
fields which need be handled by this PropertyEditorSupport class:
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) {
...
}
...
}
the image is sent to server as a Base64 String and it's added to the other params by this javascript code:
$('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]);
}
}
});
In the PropertyEditorSupport class, I read the String with the Base64 encoded image and convert to byte[]
, just to store this bytes into a file:
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();
}
but when I try open the resulting image, it isn't the same image I upload (I use the command line tool vbindiff
to verify that, and the header of the image is always the same). It's not even possible open the resulting image (I am using Gwenview on Linux/Kubuntu).
Someone can see what's wrong here?