Я ищу решение этой проблемы .. У меня есть page.jsp, и мне нужно отправить txt-файл на сервер и использовать его для чтения, используя Json и JavaScript.
Моя страница есть.
<form:form id="formFile" name="formFile" enctype="multipart/form-data" action="" method="post">
<div class="g1" style="width: 500px;">
<label for="" class="left">Select the file:</label>
<input type="file" id="fileID" name="fileID" class=""/>
</div>
<div class="g1">
<label for="" class="left"></label>
<a class="btn" id="exportFromFile" href="#" onclick="submitFile(this);">SubmitFile</a>
</div>
</form:form>
<script type="text/javascript">
function submitFile(btn){
var formData = new FormData(document.getElementById("fileID").files[0].name;
var file = '?fileID='+ document.getElementById("fileID").files[0].name;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
--- validation with Json and alerts}
};
xmlhttp.open("POST","submitFile.do"+file);
xmlhttp.setResquestHeader("Content-type","multipart/form-data ; boundary=----boundary");
xmlhttp.send(formData);
document.getElementById("fileID").value="";
};
</script>
Теперь в моем контроллере у нас есть
@RequestMapping(value="submitFile", method = RequestMethod.POST, produces = "aplication/json")
@ResponseBody
public NewSolic submitNewSolic(HttpServletRequest request, HttpServletResponse response)throws IOException{
NewSolic validation = new NewSolic();
String filename = request.getParameter("fileID");
List<String> list = new ArrayList<String>();
boolean isMultipart = ServetFileUpload.isMultipartContent(request);
if(isMultipart){
FileItemFactory factory = new DiskFileItemFactory():
ServLetFileUpload upload = new ServletFileUpload(factory);
try{
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
StringBuffer stringValues = new StringBuffer();
while (iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(item.getString() != null){
String[] itensUploadedArray = item.getString().split("\r\n");
for( String itemUploaded:itensUploadedArray){
list.add(itemUploaded);
-- use this list to a insert values after get all values in the txt--
}
}
}
}
}
Проблема в "while (iter.hasNext ())", я думаю, что файл в памяти не связан с данными,и не заполняет StringBuffer, файл содержит только цифры, но должен быть в базе данных после прочтения.