ImageRecognitionServlet.java
package videotoolkit.deeplearning.servlet;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import no.cmr.videotoolkit.deeplearning.engine.ClassificationResultJSON;
import no.cmr.videotoolkit.deeplearning.engine.ImageRecognition;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
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;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
/**
* Created by junyong on 10.02.2017.
*/
@WebServlet("/ImageRecognitionServlet")
public class ImageRecognitionServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String rootPath = Paths.get(System.getenv("WMS_HOME"), "dl4ir").toString();
String UploadImageDir = rootPath + File.separator + "upload";
if (ServletFileUpload.isMultipartContent(req))
{
System.out.println("This is multipart data");
}
String imageUrl = req.getParameter("imageUrl");
Part filePart = req.getPart("imageFile");
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
resp.setHeader("Cache-control", "no-cache, no-store");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "-1");
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
resp.setHeader("Access-Control-Max-Age", "86400");
Gson gson = new Gson();
JsonObject resultObj = new JsonObject();
ClassificationResultJSON imageRecognitionResult = new ClassificationResultJSON("result", "test result");
// new ImageRecognition().imageRecognition(imageUrl);
JsonElement result = gson.toJsonTree(imageRecognitionResult);
if (result == null)
resultObj.addProperty("success", false);
else
resultObj.addProperty("success", true);
resultObj.add("imageLabels", result);
out.println(resultObj.toString());
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doGet(req, resp);
}
}
的index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Deep learning for image recognition</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("input[name$='imageSource']").click(function () {
var source = $(this).val();
$("div.desc").hide();
$("#" + source).show();
});
$("#submitButton").click(function (e) {
e.preventDefault();
var source = $("#inputGroup input[type='radio']:checked").val();
if (source == "inputFile") {
var ext = $("input#imageFile").val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'bmp', 'tif', 'tiff']) == -1) {
alert("Seems the selected file is not image, Reselect");
return false;
}
}
var formInput = $("#imageInputForm")[0];
var formData = new FormData(formInput);
$.ajax({
type: "POST",
url: "ImageRecognitionServlet",
data: formData,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
dataType: "json",
//if received a response from the server
success: function (data, textStatus, jqXHR) {
if (data.success) {
var image = $('<img>').attr('src', data.imageUrl);
$("#resultDiv").html("");
$("#resultDiv").append(image);
}
//display error message
else {
$("#resultDiv").html("<div><b>Recognition Wrong!</b></div>");
}
},
//If there was no resonse from the server
error: function (jqXHR, textStatus, errorThrown) {
console.log("Something wrong happened " + textStatus);
$("#resultDiv").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function (jqXHR, settings) {
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#submitButton').attr("disabled", true);
},
//this is called after the response or error functions are finished
//so that we can take some action
complete: function (jqXHR, textStatus) {
//enable the button
$('#submitButton').attr("disabled", false);
$form.find("input:text, input:file, select, textarea").val('');
}
});
});
});
</script>
</head>
<body>
<div id="inputGroup" align="center" style="font-size: 20px">
<p style="color: darkblue; font-size: 24px">
<br> Deep Learning for Image Recognition</br>
</p>
<p>
Image source:
<input type="radio" id="fileRadio" name="imageSource" checked="checked" value="inputFile"/>Upload image
<input type="radio" id="urlRadio" name="imageSource" value="inputUrl"/>Image url
</p>
<form id="imageInputForm" enctype="multipart/form-data">
<div id="inputFile" class="desc">
<input id="imageFile" name="imageFile" type="file">
</div>
<div id="inputUrl" class="desc" style="display: none;">
<input id="imageUrl" name="imageUrl" type="text" size=50>
</div>
<p><input id="submitButton" type="button" value="Submit"/></p>
</form>
</div>
<br style="font-size: 12px"/>
<div id="resultSection">
<fieldset>
<legend>Image recognition results</legend>
<div id="resultDiv"></div>
</fieldset>
</div>
<form name="refresh">
<input name="visited" value="" type="hidden">
</form>
</body>
请参阅上面的代码。我想将上传文件或文本发送到servlet。所以我使用的是jQuery FormData。但是,在servlet上,它总是说请求不是多部分表单数据。我做错什么了吗。我已经检查了几乎所有关于这个的Q&amp; A,并尝试了很多方法,但仍然无法工作。非常感谢。
答案 0 :(得分:0)
将以下设置应用于jquery.ajax
来电。
mimeType: "multipart/form-data"
另外,另一方面,submit
按钮的类型为&#39;按钮&#39;,而不是类型&#39;提交&#39;。因此,您不必阻止默认操作。其次,请指定您的表单提交方法,以便发布&#39;。