如何从servlet中获取文件上传完整路径以上传它。当我打印文件名称上传时,只是让名称不是完整路径。我不知道如何获取它。我收到了这个错误。
fileField!!!!!!!! Browse
fileName!!!!!!!! fromJSON.csv
Jan 14, 2016 7:31:51 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [PriorityServlet] in context with path[/tc-eqcweb] threw exception
java.io.FileNotFoundException: fromJSON.csv (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.mongodb.gridfs.GridFS.createFile(GridFS.java:239)
at com.eqc.servlet.PriorityServlet.doPost(PriorityServlet.java:107)
我的HTML表单上传文件
<form action="priorityServlet" method="post" enctype="multipart/form-data">
<div class="col-sm-8 policytxt_align">
<div class="file_1_mas">
<a class='btn btn-primary' href='javascript:;'>
<input id="file_bal" name="Browse" type="file" value="Browse" />
</a> <br />
<div><input type="submit" value="Upload File" onClick="getExclusion();" /> </div>
<div align="center"></div>
<div></div>
</div>
我的servlet没有获取要上传的文件的完整路径:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
isMultipart = ServletFileUpload.isMultipartContent(req);
java.io.PrintWriter out = res.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("D:\\temp111"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
String fileName = null;
String fieldName = null;
String rawName = null;
try {
List fileItems = upload.parseRequest(req);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
fieldName = fi.getFieldName();
fileName = fi.getName();
}
}
System.out.println("fileField!!!!!!!! "+fieldName);
System.out.println("fileName!!!!!!!! "+fileName);
} catch (Exception ex) {
System.out.println(ex);
}
答案 0 :(得分:1)
出于安全原因,浏览器不会告诉您上传文件的path
。该文件的内容位于request
- 使用getPart
答案 1 :(得分:1)
您忘记了html代码中的enctype属性
<input id="file_bal" name="Browse" type="file" value="Browse" />
将其更改为此
<input id="file_bal" name="Browse" type="file" value="Browse" enctype="multipart/form-data"/>
只有这样你才能使用getPart
在他的帖子中指定的@ScaryWombat,您无法获取文件路径,并且您不需要它来上传文件,因为您正在使用getPart()
方法读取servlet中的文件
希望它可以帮助任何人