美文网首页
java 文件上传

java 文件上传

作者: 谢贤byte | 来源:发表于2020-12-16 17:03 被阅读0次

客户端

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="UploadFile" enctype="multipart/form-data" method="post">
        文件上传:<input type="file" name="file"><br>
        <button type="submit">上传</button>
    </form>
</body>
</html>

服务端
依赖servlet3.0以上版本

@WebServlet("/UploadFile")
@MultipartConfig
public class UploadFile extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
        //获取输入字节流
        request.setCharacterEncoding("UTF-8");
        Part part = request.getPart("file");
        InputStream input = part.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(input);
        
        //判断目录是否存在
        String path = request.getServletContext().getRealPath("/files");
        File dir = new File(path);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        
        //把文件保存到服务器
        String fileName = part.getSubmittedFileName();
        StringBuffer filePath = new StringBuffer(path).append("\\").append(fileName);    
        OutputStream output = new FileOutputStream(filePath.toString());
        byte[] bytes = new byte[bis.available()];
        bis.read(bytes);        
        output.write(bytes);
        bis.close();
        output.flush();
        output.close();
        
        System.out.println("上传成功");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.append("上传成功");
        writer.flush();
        writer.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

相关文章

网友评论

      本文标题:java 文件上传

      本文链接:https://www.haomeiwen.com/subject/hucogktx.html