Reputation: 7953
I have file upload in spring mvc it works fine in firefox but throws the following exception in IE9
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
this is what is my form :
this is what is my controller :
@RequestMapping(value = "/CIMtrek_Regional_WhseFormAddSave", method = RequestMethod.POST)
public ModelAndView CIMtrek_Regional_Whse(
@RequestParam("CIMtrek_xmlData") String CIMtrek_xmlData,
@RequestParam("CIMtrek_formName") String CIMtrek_formName,@RequestParam("fileUPload") MultipartFile uploadFile,HttpServletRequest request) {
UtilService fileUploadService = new UtilService();
if(!uploadFile.isEmpty()) {
fileUploadService.saveFile(uploadFile, request.getRealPath(""));
}
ViewContent vc = new ViewContent();
String HTML = vc.getContent(CIMtrek_xmlData, CIMtrek_formName);
List<String> ls = new ArrayList<String>();
ls.add(HTML);
logger.info("Welcome CIMtrek_Regional_Whse Add!");
return new ModelAndView("form", "list", ls);
}
file save method :
public void saveFile(MultipartFile uploadItem, String requestPath) {
File dir;
File file;
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
fileName = requestPath + "\\resources\\Attachment\\";
dir = new File(fileName);
if (!dir.exists()) {
dir.mkdirs();
}
fileName += uploadItem.getOriginalFilename();
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
outputStream = new FileOutputStream(file);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please help me to resolve this. I save file to a specified location when submitting the form.
Best Regards
Upvotes: 0
Views: 650
Reputation: 3676
Many Windows programs add the bytes 0xEF, 0xBB, 0xBF at the start of any document saved as UTF-8. This is the UTF-8 encoding of the Unicode byte order mark (BOM), and is commonly referred to as a UTF-8 BOM, even though it is not relevant to byte order.An example of this flaw is internet explorer which will render in standards mode only when it starts with a document type declaration. So i guess you need to check and skip possible BOM bytes
String enc = "ISO-8859-1"; // or NULL to use systemdefault
FileInputStream fis = new FileInputStream(file);
UnicodeInputStream uin = new UnicodeInputStream(fis, enc);
enc = uin.getEncoding(); // check and skip possible BOM bytes
InputStreamReader in;
if (enc == null) in = new InputStreamReader(uin);
else in = new InputStreamReader(uin, enc);
Sources: UnicodeInputStream
Upvotes: 1