javaweb实现文件上传小功能

2022-11-13 10:11:58 功能 文件上传 javaweb

本文实例为大家分享了javaweb实现文件上传的具体代码,供大家参考,具体内容如下

1.创建文件上传页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传页面</title>
</head>
<body>
    <fORM action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
        文件:<input type="file" name="file1"/><br>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

2.文件上传Servlet

package com.whoami.servlet;
import com.whoami.utils.UploadUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WEBServlet;
import javax.servlet.Http.httpservlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet(name = "UploadController",value = "/upload")
@MultipartConfig(maxFileSize = 1024*1024*100,maxRequestSize = 1024*1024*200)
public class UploadController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //实现文件上传

        // 1.设置乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 2.获取请求的数据
        Part part = request.getPart("file1");  //获取文件提交的数据

        // 3.获取保存文件的路径 真实路径
        String uploadPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(uploadPath);
        if(!file.exists()){
            file.mkdir(); //新建upload文件
        }

        // 4.文件上传(保存)
        //生成唯一文件名 防止文件覆盖
        String oldName = part.getSubmittedFileName();
        String newName = UploadUtils.newFileName(oldName);
        part.write(uploadPath+"\\"+newName);

        // 5. 响应客户端 上传成功!

        response.getWriter().println(part.getSubmittedFileName()+"上传成功!!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

3.生成唯一的文件名

package com.whoami.utils;
import java.util.UUID;
public class UploadUtils {
    public static String newFileName(String filename){
        return UUID.randomUUID().toString().replace("-","")+"_"+filename;
    }
}
//UUID.randomUUID().toString()会
//生成随意ID(像这样的6c0766ef-de8d-415a-83bd-fbc3ebd7a306)
//replace("-","")是用空白替换-

4.上传结果

我把文件存到了项目的WEB-INF/upload下面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关文章