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);
		}
	}

}
相关推荐
一路向北North27 分钟前
Spring Security OAuth2.0(19):JWT令牌
java·后端·spring
玛卡巴卡ldf31 分钟前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
一叶飘零_sweeeet1 小时前
IDEA 插件 Trae AI 最新全攻略(基于 TRAE AI: Coding Assistant 1.7.0.0)
java·intellij-idea·trae
KobeSacre1 小时前
CyclicBarrier 源码
java·jvm·算法
MacroZheng1 小时前
给Claude Code装上这款炫酷的HUD插件,状态信息就一目了然了!
java·人工智能·后端
我登哥MVP2 小时前
Hadoop成长史-从Nutch子项目到大数据生态王者
java·大数据·hadoop·分布式·云原生·云计算
进击切图仔2 小时前
SAM3 微调标注流水线和 Label Studio
java·服务器·前端
java1234_小锋2 小时前
Maven 4 要来了:15 年后,Java 构建工具迎来“彻底重构“
java·重构·maven
霸道流氓气质2 小时前
Java 工程师 AI 智能体学习路线 · 阶段 1:AI / LLM 基础认知 详解
java·人工智能·学习
JerrySir2 小时前
`spring.threads.virtual.enabled=true`:用三类负载定位等待、争用与拒绝
java·spring boot