仅上传图像名称以及数据库中的某些数据和Web内容中的文件夹中的图像

时间:2019-03-05 04:15:32

标签: java mysql database jsp servlets

我正在尝试上载数据库中的图像名称和一些数据,以及项目中某个文件夹中的图像,如果用户上载图像,则其名称应与一些数据一起存储在数据库中,而该图像应在Web中的某个文件夹中内容,我尝试过此操作,我只能在数据库中存储图像名称,但不存储与图像一起显示为“空”的数据

这是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文件:

<?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 个答案:

没有答案