gpt4 book ai didi

java - 使用 servlet、ajax、jquery 将图像发送到 mySQL

转载 作者:行者123 更新时间:2023-11-30 08:55:58 25 4
gpt4 key购买 nike

<分区>

尝试在不使用 ajax 刷新页面的情况下将文件上传到我的 servlet。

这几天一直卡在这上面,就是放不下。

我的表单:

<form method="POST" id="changeImage2" enctype="multipart/form-data">
<input type="file" name="photo" /> <br>
<input type="button" value="Change Picture" id="changeImage1">
</form>

我的小服务程序:

@MultipartConfig
public class changeImage extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

Part filePart = req.getPart("photo");

Object email = req.getSession().getAttribute("email");
Object name = req.getSession().getAttribute("name");

try{

Class.forName("com.mysql.jdbc.Driver");

Connection myConn = DriverManager.getConnection("", "", "");

PreparedStatement ps = myConn.prepareStatement("update user set profilePicture=? where email=? and name=?");

ps.setBlob(1, filePart.getInputStream());
ps.setString(2, (String) email);
ps.setString(3, (String) name);
ps.executeUpdate();

} catch (Exception e){
e.printStackTrace();
}
}
}

我的 ajax/jquery:

<script>
$(document).ready(function() {
$('#changeImage1').click(function() {
var dataForm = $('#changeImage2').serialize();
$.ajax({
type : 'POST',
url : 'changeImage',
data : dataForm,
success : function(data) {
$('#gg1').text(data);
},
error : function() {
$('#gg1').text("Fail");
},
});
});
});
</script>

运行时出现错误:

SEVERE: Servlet.service() for servlet [changeImage] in context with path [/Event] threw exception [org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header is null] with root cause org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header is null

我尝试使用另一种形式并且不使用 ajax/jquery:

<form action="changeImage" method="post" enctype="multipart/form-data"> 
<input type="file" name="file" />
<input type="submit" value="Change Picture" />
</form>

有了这个就可以了。所以我猜 JDBC 和 Servlet 是正确的。而且我没有正确使用 Ajax/Jquery。

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