问题:一开始项目一直启动不了,是因为用maven创建项目还导入jar包,导致lib目录冲突。 删除导入的jar包,都使用maven依赖就行了。 java.lang.IndexOutOfBoundsException * java.io.FileOutputStream.writeBytes(Native Method) * java.io.FileOutputStream.write(FileOutputStream.java:326) * com.dongmu.servlet.FileServlet.service(FileServlet.java:72) * javax.servlet.http.HttpServlet.service(HttpServlet.java:764) 这个是因为缓冲区读取的时候判断条件错误导致的。
package com.dongmu.servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; public class FileServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建工厂类 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); //创建解析器 ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); fileUpload.setHeaderEncoding("utf-8"); //使用解析器解析request对象 Listlist=null; try { list=fileUpload.parseRequest(req); for (FileItem fileItem : list) { if (!fileItem.isFormField()) { //上传文件的全部路径,String getName():获取文件字段的文件名。如果是普通字段,则返回null String name = fileItem.getName(); //注意:String getFieldName():获取表单项的name的属性值。 System.out.println("上传文件的全部路径:"+name); //获取上传文件的文件名 String filename = name.substring(name.lastIndexOf("/")+1); System.out.println("文件名"+filename); //上传文件的类型 String type = name.substring(name.indexOf(".")+1); System.out.println("上传文件的类型"+type); //使用UUID保证文件名唯一 String uuidPath= UUID.randomUUID().toString(); String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()){ uploadFile.mkdir(); } String realPath = uploadPath+"/"+uuidPath; File realuploadFile = new File(realPath); if (!realuploadFile.exists()){ realuploadFile.mkdirs(); } long size = fileItem.getSize(); System.out.println("文件的大小:"+size); //获得文件的上传流 InputStream inputStream = fileItem.getInputStream(); //获取文件的输出流 FileOutputStream outputStream = new FileOutputStream(realPath+"/"+filename); //创建一个缓冲区 byte[] bytes = new byte[1024*1024]; int len = 0; while ((len=inputStream.read(bytes))>0){ outputStream.write(bytes,0,len); } outputStream.close(); inputStream.close(); System.out.println("文件上传成功"); //上传成功清除临时文件 fileItem.delete(); } } } catch (FileUploadException e) { e.printStackTrace(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)