java完成文件上传功能

文件上传

1.      建upload.jsp

<form action="<%=request.getContextPath()%>/upload"method="post" enctype="multipart/form-data">

           <input type="file"name="file"/>

           <input type="submit"value="提交"/>

</form>

2.      建UploadServlet.class

publicclass UploadServlet extends HttpServlet {

 

// 服务器地址

private String serverPath = null;

// 文件上传目录,根据不同的操作系统要判断斜杠的方向

private String uploadPath ="upload/";

 

// 允许操作的文件类型

private String[] types = { "png","jpg", "txt" };

 

@Override

protected void service(HttpServletRequest req,HttpServletResponse res)

                    throws ServletException,IOException {

 

           // 获取服务器地址

           serverPath =req.getSession().getServletContext().getRealPath("/");

           //System.out.println(req.getSession().getServletContext());

           System.out.println(serverPath);

           // 如果文件目录不存在则去创建

           if (!new File(serverPath +uploadPath).exists()) {

                    new File(serverPath +uploadPath).mkdirs();

           }

           DiskFileItemFactory factory = newDiskFileItemFactory();

           // 设置文件的最大缓存

           factory.setSizeThreshold(5 * 1024);

           // 文件上传核心类

           ServletFileUpload upload = newServletFileUpload(factory);

           // 设置文件最大大小

           upload.setFileSizeMax(3 * 1024 *1024);

           String filePath = null;

           try {

                    // 解析请求,获取上传的文件对象列表

                    List<FileItem> items =upload.parseRequest(req);

                    for (FileItem item : items){

                             // 判断item是简单的数据还是文件,该方法如果返回false,说明是一个文件

                             if(!item.isFormField()) {

                                       // 获取文件名

                                       StringfileName = item.getName();

                                       // 获取文件类型

                                       Stringtype = fileName

                                                         .substring(fileName.lastIndexOf(".")+ 1);

                                       // 判断文件类型是否合法

                                       if(Arrays.asList(types).contains(type)) {

                                                //文件上传

                                                Stringuuid = UUID.randomUUID().toString().replace("-",

                                                                   "");

                                                //真正的文件上传路径

                                                filePath= serverPath + uploadPath + uuid + "." + type;

                                                //System.out.println(filePath);

                                                item.write(newFile(filePath));

                                       } else {

                                                thrownew RuntimeException("不是合法的文件类型");

                                       }

                             }

                    }

           } catch (Exception e) {

                    e.printStackTrace();

           }

}

3.      在web.xml中进行配置

<servlet>

           <servlet-name>uploadServlet</servlet-name>

           <servlet-class>com.niit.servlet.UploadServlet</servlet-class>

</servlet>

<servlet-mapping>

           <servlet-name>uploadServlet</servlet-name>

           <url-pattern>/upload</url-pattern>

         </servlet-mapping>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值