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

}
相关推荐
代码小将2 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点2 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx3 小时前
PYTHON训练营DAY25
java·开发语言·python
不知几秋4 小时前
数字取证-内存取证(volatility)
java·linux·前端
chxii7 小时前
5java集合框架
java·开发语言
yychen_java8 小时前
R-tree详解
java·算法·r-tree
羽球知道8 小时前
在Spark搭建YARN
前端·javascript·ajax
JANYI20188 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式
xrkhy9 小时前
反射, 注解, 动态代理
java
Ten peaches9 小时前
Selenium-Java版(操作元素)
java·selenium·测试工具·html