我希望将文件发送到数据库并能够取回,但是当我上传文件时,在servlet中由于com.prepareStatement而出现错误
我尝试强制转换,但失败了,我尝试jdbc(prepareStatement)
失败,因为我正在使用java.sql中的PreparedStatement
public class UploadServlet extends HttpServlet {
PrintWriter out = null;
Connection com = null;
PreparedStatement ps = null;
HttpSession session = null;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain/charset=UTF-8");
try {
out = response.getWriter();
session = request.getSession();
String folderName = "resources";
String uploadPath = request.getServletContext().getRealPath("") + File.separator + folderName;
File dir = new File(uploadPath);
if (!dir.exists()) {
dir.mkdirs();
}
Part filePart = request.getPart("file"); // textbox value fo name file
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String fileName = filePart.getName();
String path = folderName + File.separator + fileName;
Timestamp added_date = new Timestamp(System.currentTimeMillis());
System.out.println("fileName: " + fileName);
System.out.println("path: " + uploadPath);
System.out.println("fristName: " + firstName);
InputStream is = filePart.getInputStream();
Files.copy(is, Paths.get(uploadPath + File.separator + fileName), StandardCopyOption.REPLACE_EXISTING);
try {
com = DB.getConnectiion();
System.out.println("connection Done.");
String sql = "insert into employee1(firstname,lastname,filename,path,added_date) values(?,?,?,?,?)";
ps = com.prepareStatement(sql);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, fileName);
ps.setString(4, path);
ps.setTimestamp(5, added_date);
int status = ps.executeUpdate();
if (status > 0) {
session.setAttribute("fileName", fileName);
String msg = "" + fileName + " file uploads Successfully...";
request.setAttribute("msg", msg);
RequestDispatcher rd = request.getRequestDispatcher("/sucess.jsp");
rd.forward(request, response);
System.out.println("file uploaded Successfully...");
System.out.println("uploaded Path: " + uploadPath);
}
} catch (SQLException e) {
out.println("the Error is here " + e);
System.out.println("Exception1 is " + e);
} finally {
try {
if (ps != null) {
ps.close();
}
if (com != null) {
com.close();
}
} catch (SQLException e) {
out.println(e);
}
}
} catch (IOException | ServletException | NullPointerException e) {
out.println("Exception: " + e);
System.out.println("Exception2: " + e);
}
}
}