使用Servlet,Ajax实现上传文件的进度,要求使用JQuery来实现。前端和后端代码
时间: 2024-03-09 16:44:30 浏览: 112
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传文件进度</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label for="file">选择文件:</label>
<input type="file" name="file" id="file"><br>
<input type="button" value="上传" onclick="uploadFile()">
</form>
<div id="progress"></div>
<script>
function uploadFile() {
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: "upload",
type: "POST",
data: formData,
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var progress = e.loaded / e.total * 100;
$("#progress").text("上传进度: " + progress.toFixed(2) + "%");
}
}, false);
}
return xhr;
},
processData: false,
contentType: false,
success: function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
```
后端代码(使用Java Servlet实现):
```java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
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("/upload")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取上传文件
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String filePath = "upload/" + fileName;
File file = new File(filePath);
//上传文件
filePart.write(filePath);
//返回上传结果
out.write("上传成功!");
out.flush();
out.close();
}
}
```
这里使用了Java Servlet来处理上传请求,通过request.getPart获取上传的文件,将文件保存到指定路径中并返回上传结果。前端代码与之前的类似,通过ajax上传表单数据并监听上传进度。
阅读全文