B/S架构下实现文件上传

来源:互联网 发布:python thread sleep 编辑:程序博客网 时间:2024/04/30 08:17
public class FileUploadServlet extends HttpServlet {private Iuser user = new UserImpl();/** *持久层接口,实现方法; */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}/** *dopost里面实现文件上传方法    * List list = upload.parseRequest(request);  这个的信息是按照表单的顺序来的,可以按照顺序进行提交; */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {ServletContext context = this.getServletContext();request.setCharacterEncoding("utf-8");//DiskFileItemFactory工厂类DiskFileItemFactory factory =new DiskFileItemFactory();//创建一个文件上传解析器ServletFileUpload upload =new ServletFileUpload(factory);//文件上传的编码格式upload.setHeaderEncoding("utf-8");try {//获取到文件的集合,解析requestList list = upload.parseRequest(request);UserBean bean = new UserBean();//迭代器的使用方式,it.hasNext()和it.next()Iterator it = list.iterator();while(it.hasNext()){//获取到上传的文件对象FileItem fileItem = (FileItem) it.next();//上传过来的内容是表单里面文本内容还是文件对象if(fileItem.isFormField()){System.out.println("表单的属性:"+fileItem.getFieldName()+"表单的值:"+fileItem.getString("UTF-8"));//getParameter无法处理客户端提交过来的二进制数据/*String name = request.getParameter("name");System.out.println(name);*/}else{if(fileItem.getName()!=null && !"".equals(fileItem.getName())){System.out.println("文件的名字"+fileItem.getName());System.out.println("文件的大小"+fileItem.getSize());System.out.println("文件的类型"+fileItem.getContentType());//将文件写入到服务器。将文件名字放在数据库里面//将客户端传递过来的文件,文件是全路径,通过全路径获取到文件对象//c:\software\1.jpg  中得到1.jpgFile tempFile = new File(fileItem.getName());//在创建一个文件对象,将对象写入到服务器。path为写入服务器路径,上下文获取tomcat工程包名;String path = context.getRealPath("/")+"upload";//  path:...\web_09\upload//  savaFileNmae:  调用方法变成:时间戳_1.jpgString savaFileNmae = changeName(tempFile.getName());File file = new File(path,savaFileNmae);//将源文件传入服务器内部新写的文件路径;fileItem.write(file);//将文件的名字写入到数据库  user.add将bean传给持久层记录下来bean.setUsername("xiaowang");bean.setPwd("123");bean.setImagrPath(savaFileNmae);user.add(bean);}else{System.out.println("文件名字不符合要求");}}}    request.getRequestDispatcher("/servlet/FindServlet").forward(request, response);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}// 改变文件名的方法,避免同一个文件上传失败后无法上传;或其他同名文件;public String changeName(String fileName){long currentTime = System.currentTimeMillis();String newName = currentTime+"_"+fileName;return newName;}}

JSP端代码用户信息填写提交

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>  <!-- enctype="multipart/form-data"表示当前表单的内容以二进制的形式发送给服务器 -->    <form action="<%=request.getContextPath() %>/servlet/FileUploadServlet" method="post" enctype="multipart/form-data" >        上传人名:<input type="text" name="name" /><br/>                上传文件:<input type="file" name="file" onchange="ck(this)"/><br/>          <img alt="" src="" id="img" width="200px">          <input type="submit" name="submit" value="提交" />     </form>               <script>     function ck(obj){     console.info(obj);     var oimg = document.getElementById("img");     oimg.src=getFullPath(obj);     }          function getFullPath(obj){     //通过js代码获取到当前选中文件对象。     //操作BOM对象,BOLB对象,读取原始数据类文件对象,可以获取到计算机本地的文件。     //如果非空则为真;     if(obj){      console.info("ok");     //判断IE浏览器     if(window.navigator.userAgent.indexOf("MSIE")>=1){     obj.select();     //返回在IE下面获取到图片路径  该方法有错误!     return document.selection.createRange().text;     }else if(window.navigator.userAgent.indexOf("Firefox")>=1){     if(obj.files){         return window.URL.createObjectURL(obj.files.item(0));     }else{     return obj.value;     }     }     }     }          </script>  </body></html>

Show端jsp代码; 将信息展示出来

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'show.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <%-- <jsp:useBean id="bean" class="com.lovo.bean.UserBean" scope="request"></jsp:useBean> --%>        <form>    <label>用户名:</label>    <input type="text" value='${requestScope.bean.username}' readonly="readonly"/>    <label>密码:</label>    <input type="text" value='${requestScope.bean.pwd}' readonly="readonly"/>    //将路径传给src,src获取读取路径;    <img src="/JavaWeb11/upload/${requestScope.bean.imagrPath }" width="100px"/>    </form>  </body></html>

封装上传servlet到工具中 FileUploadUtil.java

传参(request、context)创建一个FileBean id必须有   文件名、文件大小、文件类型全局变量:request、context、map<String,String>、list<FileBean>返回参数:get方法获取MapList的数据内容;将文件写到服务器,返回的参数servlet来写到数据库;public class FileUploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}
0 0
原创粉丝点击