Servlet文件上传

文件上传涉及到的两个Jar包:

  1. com.springsource.org.apache.commons.fileupload
  2. com.springsource.org.apache.commons.io

Html部分

    <!-- form表单提交方式必须为post -->
    <!-- form必须要设置enctype="multipart/form-data"属性,否则后台无法解析 -->
    <form action="/uploading/Uploading" method="post" enctype="multipart/form-data">
        用户:<input type="text" name="username"/><br>
        上传:<input type="file" name="file"/><br>
        <input type="submit" value="提交">
    </form>

Servlet后台处理

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //工厂
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        //解析
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        //解析
        try {
            List<FileItem> fItem = sfu.parseRequest(request);
            FileItem file = fItem.get(1);
            //获取WEB-INF绝对路径
            String path = this.getServletContext().getRealPath("/WEB-INF/files"); 
            System.out.println(path);
            //获取文件名
            String fileName = file.getName();
            //检索文件名是否为绝对路径
            int isExist = fileName.lastIndexOf("\\");
            if(isExist!=-1){
                fileName = fileName.substring(isExist+1);
            }
            //解决文件重名问题
            fileName = UUID.randomUUID().toString()+ "_" + fileName ;
            //获取16进制文件名
            String hashString = Integer.toHexString(fileName.hashCode());
            //创建目录
            File fil = new File(path+"\\"+hashString.charAt(0)+"\\"+hashString.charAt(1));
            fil.mkdirs();
            //创建文件
            File saveFile = new File(fil,fileName);
            //写入文件
            file.write(saveFile);
        } catch (FileUploadException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Servlet文件上传功能可以通过使用注解@MultipartConfig将Servlet标识为支持文件上传,然后将multipart/form-data的POST请求封装成Part对象,通过Part对象对上传的文件进行操作。以下是一个文件上传Servlet示例代码: ```java @WebServlet("/uploadServlet") @MultipartConfig // 如果是文件上传,必须要设置该注解! public class UploadServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("文件上传..."); // 设置请求的编码格式 req.setCharacterEncoding("UTF-8"); // 获取普通表单项(获取参数) String uname = req.getParameter("uname"); // 表单中表单元素的name属性值 System.out.println("uname: " + uname); // 获取Part对象(Servlet将multipart/form-data的POST请求封装成Part对象) Part part = req.getPart("myfile"); // 通过Part对象得到上传的文件名 String fileName = part.getSubmittedFileName(); System.out.println("上传文件名:" + fileName); // 得到文件存放的路径 String filePath = req.getServletContext().getRealPath("/"); System.out.println("文件存放路径:" + filePath); // 上传文件到指定目录 part.write(filePath + "/" + fileName); } } ``` 而文件下载功能可以通过设置download属性来实现。以下是一个文件下载的JSP页面的示例代码: ```html <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件下载</title> </head> <body> <!-- 浏览器能够识别的资源 --> <a href="download/hello.txt">文本文件</a> <a href="download/pic.jpg">图片文件</a> <!-- 浏览器不能够识别的资源 --> <a href="download/zzz.rar">压缩文件</a> <hr> <a href="download/hello.txt" download>文本文件</a> <a href="download/pic.jpg" download="test.png">图片文件</a> <hr> <form action="downloadServlet"> 文件名:<input type="text" name="fileName" placeholder="请输入要下载的文件名"> <button>下载</button> </form> </body> </html> ``` 以上是文件上传和下载的实现方法,你可以根据需要进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值