上传数据库中的图像名称和一些数据以及项目文件夹中的图像

时间:2019-03-03 12:46:13

标签: java mysql jsp servlets image-uploading

我正在尝试上载数据库中的图像名称和一些数据以及项目中某个文件夹中的图像,如果用户上载图像,则其名称应与一些数据一起存储在数据库中,而该图像应在Webcontent中包含一些文件夹,我试过了,我只能在数据库中存储图像名称,但是不存储与图像一起显示为'null'的数据

这是jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Image Upload</title>
</head>
<body>
<form action="AddProImg" method="post"  enctype="multipart/form-data">
<input type="text" name="imgname"><br>
<input type="file" name="img">
<input type="submit" value="upload">
</form>
</body>
</html>

我的Java代码:

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/AddProImg")
public class AddProImg extends HttpServlet {

    private String filePath;
    private int maxFileSize = 1000 * 1024;
    private int maxMemSize = 1000 * 1024;
    private File file;

    public void init() {
        filePath = getServletContext().getInitParameter("file-upload");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(" C://"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practise", "root", "vicky");

            // Parse the request to get file items.
            List<?> fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator<?> i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fileName = fi.getName();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }

                    String name = request.getParameter("imgname");

                    String s = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    PreparedStatement ps = con.prepareStatement("insert into imgtable(imgname,imgpic) values(?,?)");
                    ps.setString(1, name);
                    ps.setString(2, s);
                    int z = ps.executeUpdate();

                    fi.write(file);
                    if (z != 0) {
                        out.println("Success");
                    } else {
                        out.println("Error Occured");
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

}

此web.xml文件: 在web.xml文件中,我给出了图像应存储的路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>PractiseImage</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <context-param>
    <description>Location to store uploaded file</description>
    <param-name>file-upload</param-name>
    <param-value>D:\WorkSpace\CS4U\PractiseImage\WebContent\UploadedImages\ </param-value>
  </context-param>
</web-app>

0 个答案:

没有答案