标签:NPU exist store png exception actor size system sub
一、文件上传
1.对表单的要求
(1)提交方式必须是post;
(2)上传时,enctype = "multipart/form-data";
(3)必须要有<input type="file">
2.对servlet的要求
request.getInputStream();
3.fileupload组件
comments-fileupload.jar
comments-io.jar
三个核心类
boolean ismultipartContent = ServletFileUpload.isMultipartContent(request); if (!ismultipartContent){ throw new RuntimeException("你的表单不是enctype=multipart/form-data"); } //1.创建DiskFileFactory工厂类 DiskFileItemFactory dfif = new DiskFileItemFactory(); //2.创建servletFileUpload核心对象 ServletFileUpload sfu = new ServletFileUpload(dfif); //3.解析request对象,并得到一个表单项的集合 try { List<FileItem> fileItems = sfu.parseRequest(request); for(FileItem fileItem:fileItems){ if(fileItem.isFormField()){ //是普通表单 processFormFiled(fileItem); }else{ //上传表单项 processUploadFiled(fileItem); } } } catch (FileUploadException e) { e.printStackTrace(); } }
4.FileItem提供的方法
getFeildName(); //得到字段名
getString();//得到字段的值
getName();//得到文件名
getInputStream();
isFormFeild();//判断是否是普通表单项
getContentType();//获取上传文件的MIME类型
getSize();//获取上传文件的大小
//普通表單項 private void processFormFiled(FileItem fileItem) { String fieldName = fileItem.getFieldName(); String filedValue = fileItem.getString(); System.out.println(fieldName + " = " + filedValue); }
private void processUpload(FileItem fileItem){ //得到上传的名字 String fileName = fileItem.getName(); //得到文件流 try { InputStream is = fileItem.getInputStream(); //创建存盘的路径 String realPath = this.getServletContext().getRealPath("/day18/upload"); File storeDirectory = new File(realPath ); if(!storeDirectory.exists()){ storeDirectory.mkdirs(); } //处理文件名 //fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); if(fileName!=null){ fileName = FilenameUtils.getName(fileName); }
标签:NPU exist store png exception actor size system sub
原文地址:https://www.cnblogs.com/q-1993/p/10526333.html