蒙icp备网站建设,阿里云wordpress在哪里设置,wordpress 百家模板,百度竞价效果怎么样目录
1、准备工作
2、注意事项
3、jsp页面代码
4、Servlet
5、注册Servlet 1、准备工作
导入依赖#xff1a;commons-fileupload和commons-io
2、注意事项 ①为保证服务器安全#xff0c;上传文件应该放在外界无法直接访问的目录下#xff0c;比如WEB-INF目录下 ②为…目录
1、准备工作
2、注意事项
3、jsp页面代码
4、Servlet
5、注册Servlet 1、准备工作
导入依赖commons-fileupload和commons-io
2、注意事项 ①为保证服务器安全上传文件应该放在外界无法直接访问的目录下比如WEB-INF目录下 ②为防止文件覆盖的现象发生要为上传文件产生一个唯一的文件名时间戳、uuid ③要限制上传文件的最大值 ④可以限制上传文件的类型在收到上传文件名时判断后缀名是否合法
3、jsp页面代码
注意form表单要加上 enctypemultipart/form-data 并且method一定是post因为get有大小限制
html
bodyform action${pageContext.request.contextPath}/upload.do methodpost enctypemultipart/form-data上传用户input typetext nameusernamebr/pinput typefile namefile1/ppinput typefile namefile2/ppinput typesubmit | input typereset/p
/form/body
/html
4、Servlet //判断上传的文件是普通表单还是带文件的表单if(!ServletFileUpload.isMultipartContent(req)){return;//终止方法运行说明这是一个普通表单直接返回}try {//创建上传文件袋保存路径建议在WEB-INF路径下安全用户无法直接访问上传的文件String uploadPath this.getServletContext().getRealPath(/WEB-INF/upload);File uploadFile new File(uploadPath);if(!uploadFile.exists()){uploadFile.mkdir();//创建这个目录}//缓存临时文件//临时路径假如文件超过了预期的大小。我们就把他放到一个临时文件中过几天自动删除或者提醒用户转存为永久String tmpPath this.getServletContext().getRealPath(/WEB-INF/tmp);File tmpFile new File(tmpPath);if(!tmpFile.exists()){tmpFile.mkdir();//创建这个临时目录}
1、创建DiskFileItemFactory对象
//处理上传的文件一般都需要通过流来获取我们可以使用req.getInputStream()原生态的文件上传流获取十分麻烦//建议使用Apache的文件上传组件来实现common-fileupload他需要依赖于commons-io组件//1、创建DiskFileItemFactory对象:处理文件上传路径或者大小限制的DiskFileItemFactory factory new DiskFileItemFactory(); 2、 获取ServletFileUpload
//2、获取ServletFileupload:监听文件上传进度、处理乱码问题、设置单个文件的最大值、设置总共能够上传文件的大小ServletFileUpload upload new ServletFileUpload();
3、处理上传的文件
//3、处理上传的文件//把前端请求解析封装成一个FileItem对象ListFileItem fileItems upload.parseRequest(req);for (FileItem fileItem : fileItems) {//判断上传的文件是普通表单还是带文件的表单if(fileItem.isFormField()){//普通表单String name fileItem.getFieldName();String value fileItem.getString(UTF-8);System.out.println(name:value);}else{//文件//处理文件////拿到文件名字String uploadFileName fileItem.getFieldName();System.out.println(上传的文件名uploadFileName);//可能存在文件名不合法的情况if(uploadFileName.trim().equals() || uploadFileNamenull){continue;}//获取上传的文件名String fileName uploadFileName.substring(uploadFileName.lastIndexOf(/) 1);//获取文件的后缀名String fileExtName uploadFileName.substring(uploadFileName.lastIndexOf(.) 1);//可以使用uuid保证文件名唯一//UUID.randomUUID()随机生成一个唯一的通用码String uuidPath UUID.randomUUID().toString();//存放地址//String realPath uploadPath/uuidPath;//给每个文件创建一个对应的文件夹File realPathFile new File(realPath);if(!realPathFile.exists()){realPathFile.mkdir();}//文件传输////获得文件上传的流InputStream inputStream fileItem.getInputStream();//创建一个文件输出流FileOutputStream fos new FileOutputStream(realPath / fileName);//创建一个缓冲区byte[] buffer new byte[1024*1024];//判断是否读取完毕int len 0;//如果大于0说明还存在数据while((len inputStream.read(buffer))0){fos.write(buffer,0,len);}//关闭流fos.close();inputStream.close();//上传成功清除临时文件fileItem.delete();}}} catch (FileUploadException e) {throw new RuntimeException(e);}5、注册Servlet