整天都在搜索,但仍然无法找到答案,所以我在这里 (我是Servlet编程的新手)
我有一个这样的表格:
<form onsubmit="return performUpload()">
<input type="text" id="upload-name" name="upload-name" required="required" />
<input type="text" id="upload-address" name="upload-addres" required="required" />
<input type="file" id="upload-file" name="upload-file" required="required" />
</form>
我想在将数据发送到google.maps.Geocode
之前使用JS函数中的/UploadServlet
(需要在服务器上注册纬度/经度)
我正在尝试使用XMLHttpRequest
发送数据,就像这样
//[some jquery to access form values]
var formdata=new FormData();
formdata.append("img",file);
formdata.append("upload-name",name);
//[other appends]
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//some code here (alert to confirm upload)
}
};
xhttp.open("POST","UploadServlet",true);
xhttp.send(formdata);
现在,我如何从Servlet访问所有这些参数? 如何在服务器上上传图像并根据需要使用其他参数?
我在互联网上找到了这段代码
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
//String saveDir = ?
//here I'd need to use one of the parameters i've passed through the
// ajax request;
// gets absolute path of the web application
String appPath=getServletContext().getRealPath("/")+"\\images";
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + saveDir;
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
//refines the fileName in case it is an absolute path
fileName = new File(fileName).getName();
part.write(savePath + File.separator + fileName);
}
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
哪个工作得很好,能够使用只有一个类型为“file”的输入字段的表单上传图像,而不使用
来传递JS / AJAX <form action=".." >
不幸的是,我找不到根据我的需要“调整”此代码的方法(仍然不明白request.getParts()
如何工作)
有什么建议吗?
提前致谢