介绍
在本教程中,我们将检查Ajax文件上传如何与Servlet一起使用。 同样,我们将用Bootstrap装饰表单并通过jQuery Ajax上传ajaxify文件。
实作
基本的servlet实现是相同的。 因此,我们需要做的第一件事是更新我们的web.xml文件并为我们的应用程序指定servlet。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>DemoFileUploadServlet</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>DemoFileUploadServlet</display-name>
<servlet-name>demo</servlet-name>
<servlet-class>com.jcombat.sample.DemoFileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
请注意,指定的欢迎页面为home.jsp 。 因此,当我们运行servlet应用程序时,该应用程序应该找到欢迎页面jsp和servlet类,即DemoFileUploadServlet 。
home.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
function bs_input_file() {
$(".input-file").before(
function() {
if ( ! $(this).prev().hasClass('input-ghost') ) {
var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name",$(this).attr("name"));
element.change(function(){
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function(){
element.click();
});
$(this).find("button.btn-reset").click(function(){
element.val(null);
$(this).parents(".input-file").find('input').val('');
});
$(this).find('input').css("cursor","pointer");
$(this).find('input').mousedown(function() {
$(this).parents('.input-file').prev().click();
return false;
});
return element;
}
}
);
}
bs_input_file();
$("#uploadBtn").on("click", function() {
var url = "demo";
var form = $("#sampleUploadFrm")[0];
var data = new FormData(form);
/* var data = {};
data['key1'] = 'value1';
data['key2'] = 'value2'; */
$.ajax({
type : "POST",
encType : "multipart/form-data",
url : url,
cache : false,
processData : false,
contentType : false,
data : data,
success : function(msg) {
var response = JSON.parse(msg);
var status = response.status;
if (status == 1) {
alert("File has been uploaded successfully");
} else {
alert("Couldn't upload file");
}
},
error : function(msg) {
alert("Couldn't upload file");
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>File Upload Example Using Servlet, Bootstrap and Ajax - jCombat</h3>
<form id="sampleUploadFrm" method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="file">
<span class="input-group-btn">
<button class="btn btn-default btn-choose" type="button">Choose</button>
</span> <input type="text" class="form-control"
placeholder='Choose a file...' /> <span class="input-group-btn">
<button class="btn btn-warning btn-reset" type="button">Reset</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
<div class="form-group">
<button type="button" class="btn btn-primary pull-right" id="uploadBtn">Submit</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
</form>
</div>
</div>
</body>
</html>
在home.jsp中,我们具有用于文件上传HTML表单,该表单使用Bootstrap。 我们还在顶部添加了<script>标记,该标记具有jquery代码以使表单提交操作无效。
接下来让我们创建servlet类–
DemoFileUploadServlet.java
package com.jcombat.sample;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoFileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DemoFileUploadServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String UPLOAD_DIRECTORY = "C:/uploads";
if(ServletFileUpload.isMultipartContent(request)){
try {
List multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
File fileSaveDir = new File(UPLOAD_DIRECTORY);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
} catch (Exception e) {
// exception handling
}
PrintWriter out = response.getWriter();
out.print("{\"status\":1}");
}
}
}
确保pom.xml文件添加了以下依赖项。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jcombat.sample</groupId>
<artifactId>ServletFileUploadDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Servlet with Maven Demo</name>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
执行应用程序
当执行应用程序时,我们将看到以下HTML表单。
选择文件,然后单击Submit 。 成功上传文件后,我们会收到一条警告,提示“文件已成功上传”。
下载源代码
翻译自: https://www.javacodegeeks.com/2018/09/ajax-file-upload-servlet-bootstrap.html