欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jsp+servlet简单实现上传文件功能(保存目录改进)

程序员文章站 2022-07-04 23:29:46
1、jsp前端<%-- created by intellij idea. user: lenovo date: 2020/6/19 time: 22:53 learn from https:/...

1、jsp前端

<%--
 created by intellij idea.
 user: lenovo
 date: 2020/6/19
 time: 22:53
 learn from https://www.bilibili.com/video/bv18z411i7gh?t=23&p=192
 to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
  <title>文件上传</title>
</head>
<body>
  <!--文件上传对表单的要求-->
  <!--
    1、表单中的请求提交方式必须是post
    2、表单中应指定所提交的请求位multipart请求,通过在<form/>标签中添加enctype属性
      其值为multipart/form-data
    3、 表单
  -->
  <form method="post" action="http://localhost:8888/hello/uploadimageservlet" enctype="multipart/form-data">
    编号<input type="text" name="bno"></br>
    名字<input type="text" name="bname"></br>
    照片<input type="file" name="picutreurl"></br>
    <input type="submit" value="注册">
  </form>
</body>
</html>

2、servlet后台

package servlet.bookservlet;

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.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.*;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.list;


@webservlet(name = "uploadimageservlet")
public class uploadimageservlet extends httpservlet {
  @override
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    this.dopost(request,response);
  }
  @override
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    //1、判断请求是不是multipart请求
    if(!servletfileupload.ismultipartcontent(request)){
      throw new runtimeexception("当前请求不支持文件上传");
    }
    system.out.println("开始上传文件");
    //2、创建fileitem工厂==>文件写入硬盘的作用
    try {
      diskfileitemfactory factory = new diskfileitemfactory();
      //3、创建temp临时文件夹
      string temppath ="d:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarysystem\\web\\net\\temp";
      file tempfile = new file(temppath);
      factory.setrepository(tempfile);
      //4、设置使用临时文件的边界值,大于该值,上传文件先保存在临时文件中,小于该值,则直接写入内存
      //单位是字节
      factory.setsizethreshold(1024*1024*1);

      //5、创建文件上传核心组件
      // 调用servletfileupload.parserequest方法解析request对象,得到一个保存了所有上传内容的list对象。
      servletfileupload upload = new servletfileupload(factory);
      upload.setheaderencoding("utf-8");//可以解决文件名中文乱码
      upload.setfilesizemax(1024*1024*2);

      string bno="defaultbno",bname="defaultbname";
      //6、解析请求
      list<fileitem> items =upload.parserequest(request);
      //7、遍历请求
      for(fileitem item:items){
        //普通表单项,上传名字,编号等普通信息的上i传
        if(item.isformfield()){
          string filename = item.getfieldname();// name属性值
          string filevalue = item.getstring("utf-8");// name对应的value值
          system.out.println(filename + " -- " + filevalue);
          if(filename.equalsignorecase("bno")){
            bno = filevalue;
          }
          if(filename.equalsignorecase("bname")){
            bname = filevalue;
          }
         }
        else{//上传图片等
          string filename = item.getname();
          system.out.println("上传文件名字:"+filename);
          string suffix = filename.substring(filename.lastindexof('.'));//获取文件类型
          string newfilename = bno+"_"+bname+suffix;
          system.out.println(newfilename);
          //获取输入流,其中有上传文件的内容
          inputstream is = item.getinputstream();
          //string path = this.getservletcontext().getrealpath("/net/bookimage");//获得当前项目保存服务器地址,也就是web文件夹下
          string path ="d:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarysystem\\web\\net\\bookimage";
          //文件夹内文件数目有上限,但是可以创建子目录
            //获取当前系统时间
            calendar now = calendar.getinstance();
            int year = now.get(calendar.year);
            int month = now.get(calendar.month)+1;
            int day = now.get(calendar.day_of_month);
            path = path+"/"+year+"/"+month+"/"+day;
            //若该目录不存在,直接创建新目录
            file dirfile = new file(path);
            if(!dirfile.exists()){
              dirfile.mkdirs();
            }
          //创建目标文件,用来保存上传文件
          file desfile = new file(path,newfilename);
          //创建文件输出流
          outputstream os = new fileoutputstream(desfile);
          //将输入流数据写入到输出流中
          int len=-1;
          byte[]buf = new byte[1024];
          while((len=is.read(buf))!=-1){
            os.write(buf,0,len);
          }
          //desfile.delete();//删除临时文件
          os.close();//输出流
          is.close();//输入流
          //删除临时文件
          item.delete();
        }
      }
    } catch (fileuploadexception e) {
      e.printstacktrace();
    }
  }
}

总结

到此这篇关于jsp+servlet简单实现上传文件(保存目录改进)的文章就介绍到这了,更多相关jsp servlet实现上传文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!