通过ajax将文件(PDF)发送到JSP Servlet可以通过以下步骤实现:
以下是一个示例代码:
前端代码(HTML + JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadFile()">上传文件</button>
<script>
function uploadFile() {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'uploadServlet', // JSP Servlet的URL
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log('文件上传成功');
},
error: function() {
console.log('文件上传失败');
}
});
}
</script>
</body>
</html>
JSP Servlet代码:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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("/uploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String savePath = "指定保存文件的路径"; // 设置保存文件的路径
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
Part part = request.getPart("file");
String fileName = getFileName(part);
OutputStream out = null;
InputStream filecontent = null;
try {
out = new FileOutputStream(new File(savePath + File.separator + fileName));
filecontent = part.getInputStream();
int read = 0;
byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
}
}
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length() - 1);
}
}
return "";
}
}
以上代码演示了如何通过ajax将文件(PDF)发送到JSP Servlet,并在服务器端保存文件。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云