我有一个文件(data
),我使用XMLHtppRequest
JS对象发送给servlet。我对此没有任何问题。我在servlet中通过request.getInputStream()
收到它,解析它并完美地获取文件。当我还必须发送/接收文件的名称时出现问题。我试图将该文件名放在<input type="hidden">
内并在javascript中发送它调用submit()
方法。关键是我不能&#39;从servlet使用request.getParameter("fileName");
(它总是为空)来获取它,我不知道我做错了什么或者我不能拥有{{1加上一个submit()
(两个POST)。
使用Javascript:
XMLHtmlRequest.send()
Servlet doPost方法:
function save(data){
var loadedFilename = "exampleFileName";
var xhr = new XMLHttpRequest();
var base64data = (new core.Base64()).convertUTF8ArrayToBase64(data);
xhr.open("POST", "ServletUpload", true);
xhr.send(base64data);
document.getElementById("fileName").value = loadedFilename;
document.forms["formExample"].submit();
}
HTML表单:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String fileName = request.getParameter("fileName");
byte[] content = Base64.decodeBase64(IOUtils.toByteArray(request.getInputStream()));
ByteArrayInputStream input = new ByteArrayInputStream(content);
FileOutputStream file = new FileOutputStream("/home/user/Documents/workspace/tests/editingTests.odt");
IOUtils.copy(input, file);
input.close();
file.close();
}
答案 0 :(得分:1)
function save(data){
var loadedFilename = "exampleFileName";
var xhr = new XMLHttpRequest();
var base64data = (new core.Base64()).convertUTF8ArrayToBase64(data);
//changing this line should fix the problem
xhr.open("POST", "ServletUpload"+"?fileName="+loadedFilename , true);
xhr.send(base64data);
//following two lines are not needed
//document.getElementById("fileName").value = loadedFilename;
//document.forms["formExample"].submit();
}