用ajax实现文件上传需要两个jar包
html代码
<form name="myform" id="myform" method="post" enctype="multipart/form-data" >
<input type='file' name="myfile" id="image" accept='image/jpeg,image/png,image/jpg,image/gif'/>
<button type="button" onclick="upload()">图片上传</button></td></tr>
</form>
js代码(需要添加jquery依赖)
<script type="text/javascript">
//提交文件
function uploadFile(){
var fileObj = $("#image")[0].files[0]; //获取file对象
var FileController = getPath() + "/admin1?method=uploadFile";//此处填写servlet路径
var form = new FormData();
form.append("file", fileObj);
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.onload = function () {
// alert("上传完成!");
};
xhr.send(form);
}
// 获取项目的相对地址
function getPath() {
var pathName = window.location.pathname.substring(1);
var webName = pathName == '' ? '' : pathName.substring(0,
pathName.indexOf('/'));
if (webName == "") {
return window.location.protocol + '//'
+ window.location.host;
} else {
return window.location.protocol + '//'
+ window.location.host + '/' + webName;
}
}
</script>
servlet代码
//文件上传
public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
System.out.println("开始上传");
DiskFileItemFactory fu = new DiskFileItemFactory();
fu.setSizeThreshold(2 * 1024 * 1024);
fu.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(fu);
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = null;
try {
fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
item.getString("UTF-8");
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name1 = item.getName();//获取上传的文件名
long size = item.getSize();//获取上传的文件大小(字节为单位)
if ((name1 == null || name1.equals("")) && size == 0) {
continue;//跳到while检查条件
}
int end = name1.length();
int begin = name1.lastIndexOf("\\");
String newname = name1.substring(begin + 1, end);
if (newname.length() == 0) {
System.out.println("上传文件导入异常,请重新上传...");
} else {
try {
//保存文件
File savedFile = new File("/code", name1);//用原文件名,作为上传文件的文件名。“/code”为目标路径
item.write(savedFile);
item.delete();
System.out.println("上传结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}