如何使用servlet和jsp将文件插入java中的数据库
如何使用servlet和jsp将文件插入数据库 帮助我将文件插入数据库 1.Servlet文件如何使用servlet和jsp将文件插入java中的数据库,java,jsp,servlets,Java,Jsp,Servlets,如何使用servlet和jsp将文件插入数据库 帮助我将文件插入数据库 1.Servlet文件 2.jsp文件 在此处插入标题 ${message} 姓名: 选择文件: 我在'filePart'中获取空值,如何从jsp获取文件值以插入数据库表单应具有enctype=“multipart/form data”。可能存在重复的 package FileUpload; import java.io.IOException; import java.io.InputStr
2.jsp文件
在此处插入标题
${message}
姓名:
选择文件:
我在'filePart'中获取空值,如何从jsp获取文件值以插入数据库表单应具有
enctype=“multipart/form data”
。可能存在重复的
package FileUpload;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
public class UploadImage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher rd=req.getServletContext().getRequestDispatcher("/jsp/upload.jsp");
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name=req.getParameter("name");
InputStream in=null;
Part filePart=req.getPart("photo");
if(filePart!=null){
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
in=filePart.getInputStream();
}
ConnectionUtil cu=new ConnectionUtil();
Connection conn =cu.getConnection();
String sql = "insert into upload(name,photo)values(?, ?)";
try {
PreparedStatement pt = conn.prepareStatement(sql);
pt.setString(1,name);
pt.setBlob(2,in);
int row = pt.executeUpdate();
if (row > 0) {
req.setAttribute("message", "File uploaded and saved into database");
}
RequestDispatcher rd=req.getServletContext().getRequestDispatcher("/jsp/upload.jsp");
rd.forward(req, resp);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/ram_jsp/upload" method="post">
<table>
<tr><td>${message}</td></tr>
<tr><td>Name :</td><td><input type="text" name="name"></td></tr>
<tr><td>Choose File:</td><td><input type="file" name="photo" size="100"></td></tr>
<tr><td><input type="submit" value="Upload">
</table>
</form>
</body>
</html>