ajax+servlet实现文件上传

用ajax实现文件上传需要两个jar包
文件上传所需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();
			} 
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值