gpt4 book ai didi

javascript - 使用多数据表单上传文件时,通过 ajax 调用从服务器获取响应

转载 作者:太空宇宙 更新时间:2023-11-04 13:19:35 24 4
gpt4 key购买 nike

我的项目遇到了一些问题。你好,有几个 jsp 和 Java 类。在一个jsp中,我创建一个只有输入类型="file"和类型=“提交”的表单,然后我有一个ajax调用并将所有表单数据发送到我的服务器上的doPost类。然后我将该文件发送到数据库,一切顺利,我的问题是我想将 id 从数据库返回到 .jsp。我可以访问并打印 doPost 来检查我的 key ,但无法将其发送到 ajax 调用内的成功函数。这是我的代码,我非常感谢任何形式的帮助,谢谢!

<form id="uploadDocuments" target="invisible"  method="POST" action="UploadDocumentsAjaxService" enctype="multipart/form-data">
<iframe name="invisible" style="display:none;"></iframe>
<h3 style="width: 71%;margin-left: 8%;">ANEXAR FICHEIROS:</h3>
<h4 style="margin-left: 8%; color: #F7A707" >Escolher ficheiro para anexar: </h4>
<input type="file" id="file_input" name="file" size="50" style="width: 60%; margin-left: 8%;"/>
<input type="submit" value="Upload" />
</form>

我有我的 Ajax 调用:

$("#uploadDocuments").submit(function (e) {
alert(10);
alert($("#uploadDocuments").attr('action'));
$.ajax({
type: $("#uploadDocuments").attr('method'),
url: $("#uploadDocuments").attr('action'),
contentType: $("#uploadDocuments").attr( "enctype"),
data: new FormData($("#uploadDocuments")[0]),
processData: true,
success: function (data) {
alert("submitDocument");
alert();
/* key = data;
addFilesToTable(key); */
return true;
}
});
e.preventDefault();
$(form).off('submit');
return false;
});

然后是我的 servlet 类:

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
response.setContentType("text/html;charset=ISO-8859-1");

PrintWriter out = response.getWriter();

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
ChangeEntityRequestActionBean actionBean = new ChangeEntityRequestActionBean();

if(!isMultipart)
return;

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);

// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
String fileName = "";
Long documentKey = null;
String key = "";

try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (!item.isFormField()) {
fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
documentKey = actionBean.insertDocument(item, fileName);

System.out.println("Key from DAO ------->>>>>"+documentKey);
key = String.valueOf(documentKey);

}

System.out.println("Key in String from DAO ----->"+key);
System.out.println();

out.println("success");
response.flushBuffer();
}catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
} finally {
out.close();
}


}

我想要的只是将键值发送到 out.println,这样我就可以在 jquery 函数上使用该值

最佳答案

在 servlet 中 doPost() 的第一行中,将响应的内容类型更改为“application/json”。然后将 JSON 字符串写入输出流。有libraries可以为您执行此操作,但对于如此简单的事情,您可以自己编写 JSON。这实际上可能有一个优势,因为你的 key 是 java long ;将其视为字符串,您不必担心整数如何表示。

// replace out.println("success"); with this:
out.print("{\"key\": \"" + key + "\"}");

然后在成功回调函数中,您可以将键作为 data 对象的字段进行访问。您需要在 ajax 方法中指定数据类型 (dataType: 'json')。

success: function (data) {
var key = data['key'];
addFilesToTable(key);
return true;
}

关于javascript - 使用多数据表单上传文件时,通过 ajax 调用从服务器获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com