JSP实现图片上传并保存到数据库

JSP实现图片上传并保存到数据库,第1张

servlet里面有一个request.getPart()方法,通过这个文件可以获得图片,前提是你的servlet版本必须是3.0以上+tomcat7,具体参考以下

@WebServlet("/articleManage")

@MultipartConfig(maxFileSize = 1024 * 1024 * 10)

// 最大10MB

public class ArticleManage extends HttpServlet {

private static final long serialVersionUID = 1L

public ArticleManage() {

super()

}

protected void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("utf-8")

doPost(request, response)

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String method = request.getParameter("method")

if (method != null) {

if (method.equals("add")) {

addArticle(request, response)

}

}

private void addArticle(HttpServletRequest request,

HttpServletResponse response) {

ArticleService service = new ArticleServiceImpl()

ArticleTypeService typeService=new ArticleTypeServiceImpl()

String content = null

String email = null

String tag = null

String type=null

try {

email = request.getParameter("email")

content = request.getParameter("content")

tag = request.getParameter("tag")

type=request.getParameter("type")

Part img = request.getPart("img")

String imgName = null

if (img != null) {

// 设置文件路径,写到硬盘

String head = img.getHeader("content-disposition")

int index = head.lastIndexOf("=") + 2

imgName = head.substring(index, head.length() - 1)// 上传文件时的文件名

imgName.lastIndexOf(".")

String suffix = imgName.substring(imgName.lastIndexOf("."))// 文件后缀

if (!suffix.equals(".jpeg") &&!suffix.equals(".jpg")

&&!suffix.equals(".png") &&!suffix.equals(".gif")

&&!suffix.equals(".bmp")) {

System.out.println("innn******************")

// 非法文件

request.setAttribute("content", content)

request.setAttribute("email", email)

request.setAttribute("tag", tag)

request.setAttribute("type", type)

request.setAttribute("errorinfo",

"*您上传的文件不合法,只能上后缀为jpg,bmp,png,gif,jpeg的图片")

request.getRequestDispatcher("add.jsp").forward(request,

response)// 重新导航到表单页

return

}

imgName = System.currentTimeMillis() + suffix

img.write(this.getServletContext().getRealPath("/image/upload")

+ File.separator + imgName)// 写到硬盘

}

Article msg = new Article()

msg.setContent(content)

msg.setImg("image/upload/" + imgName)

msg.setEmail(email)

msg.setKeyWord(tag)

msg.setType(typeService.querySingle(Integer.parseInt(type)))

// 从session中取User

User user = (User) request.getSession().getAttribute("user")

msg.setUser(user)

service.addMsg(msg)

response.setCharacterEncoding("utf-8")

response.setContentType("text/html")

response.getWriter()

.write("<html !DOCTYPE html><body><div style='marginautofont-weight:bold'><span style='font-size17px'>投稿成功</span>两秒后跳转到首页...</body></html>")

response.setHeader("refresh", "2url=index.jsp")

} catch (Exception e) {

e.printStackTrace()

request.setAttribute("content", content)

request.setAttribute("email", email)

request.setAttribute("tag", tag)

request.setAttribute("type", type)

request.setAttribute("errorinfo", "投稿失败,请检查上传文件的大小,不能大于10MB")

try {

request.getRequestDispatcher("add.jsp").forward(request,

response)

} catch (ServletException | IOException e1) {

e1.printStackTrace()

}

return

} finally {

try {

service.closeConnResources()

} catch (SQLException e) {

e.printStackTrace()

}

}

}

这是我前几天写的,有问题再问我

获取表单中的信息,然后插入到Mysql中 

<%@ page language="java" contentType="text/html charset=gbk"

    pageEncoding="gbk"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%

int id = Integer.parseInt(request.getParameter("id"))

int rootid = Integer.parseInt(request.getParameter("rootid"))

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=gbk">

<title>Replay</title>

</head>

<body>

<form method="post" action="ReplayOK.jsp">

 <input type="hidden" name="id" value="<%=id %>">

 <input type="hidden" name="rootid" value="<%=rootid %>">

<table align="center">

 <tr>

  <td>

   <input type="text" name="title" size="80">

  </td>

 </tr>

 <tr>

  <td>

   <textarea cols="80" rows="20" name="cont"></textarea>

  </td>

 </tr>

 <tr>

  <td>

   <input type="submit" value="提交">

  </td>

 </tr>

</table>

</form>

</body>

</html>

---------------------------------------------------------------

下面接收上面表单中传过来的信息,并插入到mysql中

<%@ page language="java" contentType="text/html charset=gbk"

    pageEncoding="gbk"%>

<%@ page import="java.sql.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%

request.setCharacterEncoding("GBK")

int id = Integer.parseInt(request.getParameter("id"))

int rootid = Integer.parseInt(request.getParameter("rootid"))

String title = request.getParameter("title")

String cont = request.getParameter("cont").replaceAll("\n","<br/>")

Connection conn = null

Statement st = null

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

conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=690115399")

st = conn.createStatement()

conn.setAutoCommit(false)

String sql = "insert into article values(null,?,?,?,?,now(),0)"

PreparedStatement pstmt = conn.prepareStatement(sql)

pstmt.setInt(1,id)

pstmt.setInt(2,rootid)

pstmt.setString(3,title)

pstmt.setString(4,cont)

pstmt.executeUpdate()

st.executeUpdate("update article set isleaf = 1 where id = " + id)

conn.commit()

conn.setAutoCommit(true)

st.close()

pstmt.close()

conn.close()

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=gbk">

<title>Insert title here</title>

</head>

<body>

<%response.sendRedirect("ShowArticleTree.jsp") %>

</body>

</html>

当然最好的方法还是应该用jsp + JavaBean方式。

....首先..可以选择Apache里面的upload包....这个是把文件传到服务器上的上传组件....然后是存到数据库里....那就要看你什么数据库了....比如Oracle..就是Blob至Access...就是

对象

字段....存取方法都是不一样的..要分别对待

有个通用方法,你找到图片文件之后,建立输入流,然后创建bytearrayoutputstream,然后从输入流中读字节到后面那个流中,并冲它里面产生字节数组保存到byte字段中

其实建议你不要将图片直接上传到数据库

图片上传到数据库要用到

blob大对象(以oracle为例),这样影响程序性能,你可以将图片上传到指定文件夹,同时将图片保存的路径+文件名上传到数据库,要显示就读取这个这个路径找到图片,然后显示.刚做了个这个代码


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9966030.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-03
下一篇2023-05-03

发表评论

登录后才能评论

评论列表(0条)

    保存