我正在尝试使用带有java后端的webkitdirectory实现文件上传功能。
步骤1。使用webkitdirectory设计HTML表单
<form action="DataUpload" method="post" enctype="multipart/form-data">
<input type="text" name="dbName" value="Database Name Here" id="dbName"/>
<input type="file" id="ctrl" webkitdirectory directory multiple/>
<input type="submit" />
</form>
第2步。将信息从form
传递到Servlet
public class DataUpload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response){
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator fileIterator;
try {
fileIterator = upload.getItemIterator(request);
InputStream inputStream = null;
BufferedReader br = null;
System.out.println("CheckPoint 1");
while(fileIterator.hasNext()) {
System.out.println("CheckPoint 2");
FileItemStream item = fileIterator.next();
String inputFileName = FilenameUtils.getName(item.getName());
inputStream = item.openStream();
inputFileName = inputFileName.split("\\.")[0];
List<String[]> list = new ArrayList<String[]>();
// Getting File
br = new BufferedReader(new InputStreamReader(inputStream)); // Getting the object to read file
String line;
while((line = br.readLine())!= null){// While condition ends then end of file is reached.
list.add(line.split(","));
}
// Checking if File is Empty
if (list.size() == 0){
System.err.println("File Empty");
}else{
// TODO : Parameter Parser.
// DO JOB HERE
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我的代码不会给出任何编程错误,但它不会通过CheckPoint 2
,即它不会进入while
循环。我试着查看各种帖子,例如:
Keep Directory Structure When Uploading
How to upload files to server using JSP/Servlet? - 虽然此问题与所讨论的问题最相似,但This问题适用于选择文件夹中的多个文件,此处的问题是将文件上传到文件夹内的不同子目录中。
我想知道,如果可以单独使用java servlets
而不使用javascript
。我能够在一个文件夹中上传多个文件。但是,当我选择一个文件夹作为输入时,代码似乎不起作用,而是当我选择一个特定文件或一个文件子集时它可以工作。
答案 0 :(得分:0)
HTML文件表单
<form onsubmit="readFiles()">
<input type="file" name="files" webkitdirectory directory multiple id="files">
<input type="submit">
</form>
JavaScript函数
function readFiles(){
var files = document.getElementById("files").files;
for (var file = 0 ; file < files.length; file++) {
var reader = new FileReader();
reader.onload = function(e){
var object = new Object();
object.content = e.target.content;
var json_upload = "jsonObject=" + JSON.stringify(object);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "http://localhost:8080/readFileServlet");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
}
reader.readAsBinaryString(files);
}
}
Java功能:
JSONObject jObj = new JSONObject(request.getParameter("jsonObject"));
答案 1 :(得分:-1)
在post方法中尝试
make @Autowired ServletContext c
;
或者在servlet中从中获取对象
byte[] bytes = file.getBytes();
String UPLOAD_FOLDEdR=c.getRealPath("/images");
Path path = Paths.get(UPLOAD_FOLDEdR +"/"+ file.getOriginalFilename());
Files.write(path, bytes);