AJAX 文件上传进度条 JAVA

=======JSP文件

html 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>AJAX 文件上传进度条</title>
    <style>
        #smallrainContainer {
            width: 300px;
            border: 1px solid red ;
            margin-top: 10px;
        }
        #smallrainBar {
            height: 20px;
            background-color: blue;
            width: 0%;
        }
    </style>
</head>
<body>
<h3>AJAX 文件上传进度条</h3>


<h3>请选择较大的文件进度条才看的清楚</h3>
    <input type="file" id="smallrainInput" name="smallrainInput">
   
    <div id="smallrainContainer">
        <div id="smallrainBar"></div>
    </div>
 <button onclick="uploadFile()">上传文件</button>

    <script>
        function uploadFile() {
            const fileInput = document.getElementById('smallrainInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择要上传的文件');
                return;
            }

            const formData = new FormData();
            formData.append('smallrainfileInput', file);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'smallRainAJAXUpload', true);

            xhr.upload.addEventListener('progress', function (event) {
                if (event.lengthComputable) {
                    const percentComplete = (event.loaded / event.total) * 100;
                    const progressBar = document.getElementById('smallrainBar');
                    progressBar.style.width = percentComplete + '%';
                }
            });
            xhr.onload = function () {
                if (xhr.status === 200) {
                    alert('文件上传成功');
                } else {
                    alert('文件上传失败');
                }
            };

            xhr.send(formData);
        }
    </script>
</body>

</html>

======JAVA文件

java 复制代码
package org.rain.ajax;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
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;

@WebServlet("/smallRainAJAXUpload")
@MultipartConfig()
public class MulAJAXUpload extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String shead = new String(
				"<head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"> </head>");
		out.println("<html>");
		out.print(shead);
		out.println("您访问的路径不存在,非法访问");
		out.println("</body>");
		out.println("</html>");
	}

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

		String savePath = "C:/SmallRian";
		boolean hasFile = false;
		try {
			File fileSaveDir = new File(savePath);
			if (!fileSaveDir.exists()) {
				fileSaveDir.mkdir();
			}

			Part filePart = request.getPart("smallrainfileInput");
			String fileName = filePart.getSubmittedFileName();

			String localFile = savePath + "/" + fileName;
			if (null != fileName && fileName.length() > 0 && filePart.getSize() > 0) {
				filePart.write(localFile);
				hasFile = true;
			} else {
				hasFile = false;
			}

		} catch (IOException e) {
			response.sendError(500);
			throw new ServletException("没有上传成功", e);
		}
	}

}
相关推荐
Learner几秒前
Python异常处理
java·前端·python
tao3556673 分钟前
VS Code登录codex,报错(os error 10013)
java·服务器·前端
信创天地10 分钟前
核心系统去 “O” 攻坚:信创数据库迁移的双轨运行与数据一致性保障方案
java·大数据·数据库·金融·架构·政务
mjhcsp12 分钟前
C++ AC 自动机:原理、实现与应用全解析
java·开发语言·c++·ac 自动机
huihuihuanhuan.xin13 分钟前
后端八股之java并发编程
java·开发语言
茶本无香17 分钟前
设计模式之二—原型模式:灵活的对象克隆机制
java·设计模式·原型模式
寻星探路17 分钟前
【算法通关】双指针技巧深度解析:从基础到巅峰(Java 最优解)
java·开发语言·人工智能·python·算法·ai·指针
小北方城市网27 分钟前
微服务接口设计实战指南:高可用、易维护的接口设计原则与规范
java·大数据·运维·python·微服务·fastapi·数据库架构
什么都不会的Tristan31 分钟前
HttpClient
java·微信登录
隐退山林32 分钟前
JavaEE:多线程初阶(二)
java·开发语言·jvm