web上传本地图片并存到mysql数据库的Java代码
时间: 2024-05-04 13:15:59 浏览: 74
在java web中显示存入mysql数据库的图片
请参考以下Java代码:
1.实体类
```java
public class Image {
private int id;
private String imageName;
private String imagePath;
//getters and setters
}
```
2.DAO类
```java
public class ImageDao {
public int saveImage(Image image) {
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try {
conn = DBConnectionUtil.getConnection();
String sql = "INSERT INTO image(image_name, image_path) VALUES (?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, image.getImageName());
ps.setString(2, image.getImagePath());
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBConnectionUtil.closeConnection(conn, ps, null);
}
return result;
}
}
```
3.Servlet类
```java
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取文件上传路径
String savePath = this.getServletContext().getRealPath("/upload/");
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
System.out.println("目录不存在,需要创建!");
file.mkdir();
}
//获取上传的文件
Part part = request.getPart("file");
String fileName = part.getSubmittedFileName();
String filePath = savePath + File.separator + fileName;
part.write(filePath);
//存储文件信息到数据库
ImageDao dao = new ImageDao();
Image image = new Image();
image.setImageName(fileName);
image.setImagePath(filePath);
dao.saveImage(image);
//返回上传结果
out.println("<script>");
out.println("alert('文件上传成功!');");
out.println("window.location.href = 'index.jsp';");
out.println("</script>");
}
}
```
4.HTML代码
```html
<form method="post" action="UploadServlet" enctype="multipart/form-data">
选择文件:<input type="file" name="file"/><br/><br/>
<input type="submit" value="上传"/>
</form>
```
以上就是web上传本地图片并存到mysql数据库的Java代码。希望对您有所帮助!
阅读全文