package cn.itcast.servlet; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使用第三方组件上传文件 /** * 步骤 * 1、创建一个磁盘文件项的工厂 * 2、创建一个核心解析类ServletFileUpload * 3、解析request对象,返回一个List<FileItem> */ //创建一个磁盘文件项的工厂 DiskFileItemFactory factory=new DiskFileItemFactory(); //创建一个核心解析类ServletFileUpload ServletFileUpload fileUpload=new ServletFileUpload(factory); //解析request对象,返回一个List<FileItem> try { List<FileItem> list=fileUpload.parseRequest(request); for(FileItem fileItem:list) { if(fileItem.isFormField()) { //页面中的普通项 String name=fileItem.getFieldName(); //获得普通项的值 String value=fileItem.getString(); System.out.println(name+" "+value); } else { //文件上传项 //获得文件的名称 String fileName=fileItem.getName(); //获得文件的数据 InputStream is=fileItem.getInputStream(); //向服务器端写文件 //获得上传文件的路径 String path=getServletContext().getRealPath("/upload"); OutputStream os=new FileOutputStream(path+"/"+fileName); //俩流对接 int len=0; byte[] b=new byte[1024]; while((len=is.read(b))!=-1) { os.write(b, 0, len); } is.close(); os.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <%@ 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 ""upload.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> <h1>文件上传</h1> <form action="${pageContext.request.contextPath }/UploadServlet" method="post" enctype="multipart/form-data"> 文件描述:<input type="text" name="desc"/><br/> 文件上传:<input type="file" name="upload"><br/> <input type="submit" value="上传"> </form> </body> </html> |
|
20分 |
跟踪代码,应该文件名是全路径D:\PHOTO\XXX.JPG导致的,只要截取最后的xxx.jpg
|
10分 |
你的路径封装的明显有问题啊,又是e盘又是d盘的
|
10分 |
路径有问题,找不到文件报错
|