1.使用XMLHttpRequest对象发送文件
js代码如下:
var form = new FormData();
var xhr = new XMLHttpRequest();
for (var i = 0, file; file = this.fileFilter[i]; i++) {
form.append("file", file);
}
xhr.open("POST", self.url, true);
xhr.send(form);
使用springmvc的MultipartFile[] files参数接收不到文件,而直接表单提交是可以收到文件的,因此另谋出路,使用servlet进行接收。
2.servlet接收代码如下:
private String uploadPath;
File tempPathFile;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName="";
String str="";
try {
// Create a factory for disk-based file items
uploadPath=request.getSession().getServletContext()
.getRealPath("/") + "upload/" ;
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096);
factory.setRepository(tempPathFile);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(new String(fi.getName().getBytes(), "utf-8"));
File savedFile = new File(uploadPath, fullFile.getName());
if (!savedFile.getParentFile().exists())
savedFile.getParentFile().mkdirs();
fi.write(savedFile);
str=str+fullFile.getName()+"*";
}
}
} catch (Exception e) {
System.out.print(e);
}
response.getWriter().write("上传成功!");
}
3.servlet使用springmvc的注解需要加如下代码:
@Autowired
private TestDao testdao;
public void init(ServletConfig config) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
4.整体效果图如下