ajax异步上传图片及其他表单项

来源:互联网 发布:网站 seo 编辑:程序博客网 时间:2024/06/05 09:31
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script></head><script type="text/javascript">function upload() {var formData =new FormData($("#form")[0]); $.ajax({ url:'${pageContext.request.contextPath }/UploadServlet', data:formData, type:'post', processData:false, contentType:false, success:function(data){alert("成功了!") } });    }</script><body><form id="form" id="form">文件名:<input id="name" name="name" type="text" /><br/>上传文件:<input type="file" name="file"/><br/><input type="button" value="提交" onclick="upload()"/><br/></form></body></html>


try {//接受上传文件//1、创建磁盘文件项工厂DiskFileItemFactory factory = new DiskFileItemFactory();//2、创建文件上传的核心类ServletFileUpload upload = new ServletFileUpload(factory);//3、解析request---获得文件项集合List<FileItem> parseRequest = upload.parseRequest(request);//4、遍历文件项集合for(FileItem item : parseRequest){//5、判断普通表单项/文件上传项boolean formField = item.isFormField();//是否是一个普通表单项if(formField){//普通表单项System.out.println(item.getFieldName() + ":" + item.getString());}else{//文件上传项//我们使用uuid生成文件名以防止乱码String fileName = UUID.randomUUID().toString().replace("-","").trim();fileName = fileName + ".jpg";//获得上传文件的内容InputStream in = item.getInputStream();//将in中的数据拷贝服务器上String path = this.getServletContext().getRealPath("products");OutputStream out = new FileOutputStream(path+"/"+fileName);int len = 0;byte[] buffer = new byte[1024];while((len=in.read(buffer))>0){out.write(buffer, 0, len);}in.close();out.close();}}} catch (FileUploadException e) {e.printStackTrace();}



原创粉丝点击