java - 仅上传图像名称以及数据库中的一些数据,并且仅图像应存储在网页内容的文件夹中

标签 java mysql database jsp servlets

我正在尝试上传图像名称和数据库中的一些数据以及项目中某个文件夹中的图像,如果用户上传图像,则其名称应与一些数据一起存储在数据库中,并且该图像应存储在网络中的某个文件夹中内容,我尝试了这个,我只能在数据库中存储图像名称,但数据和图像不会存储,显示为“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:

<?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\Realestate\WebContent\UploadedImages\ </param-value>
  </context-param>
</web-app>

最佳答案

无法使用

获取参数
String name = request.getParameter("imgname");

您需要编写如下所示的其他条件

    if (!fi.isFormField()) { 
  //to read parameter and value

     String name = fi.getFieldName();
     String value = fi.getString();

我认为这应该有效

关于java - 仅上传图像名称以及数据库中的一些数据,并且仅图像应存储在网页内容的文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996426/

相关文章:

php - CakePHP 链接插件下拉列表未链接

java - Mapstruct:结果类型 com.integrator.license.License 中存在未知属性 "updateDate"。您的意思是 "updatedDate"吗?

java - 使用方面注释将类型间声明从 .aj 转换为 .java

java - 如何正确重写 JacksonAnnotationIntrospector._findAnnotation 以替换元素的注释

MySQL:如果不在则选择(除非库存> 0)

php - 如何从数组中获取列名并导出到excel

c# - 将 Xamarin 连接到 Python MySQL 连接器

java - Insert INTO 查询不适用于一种方法但适用于另一种方法

mysql - "Cascade"外键通过多个表?

Java类型删除: Rules of cast insertion?