繁体   English   中英

将上传文件的文件名存储在数据库Java中

[英]Store filename of uploaded file in database java

我正在使用http://codejava.net/coding/upload-files-to-database-servlet-jsp-mysql网站上的程序,该程序允许用户上载数据库中的文件。 到目前为止,我将数据插入数据库没有任何麻烦。

我想在数据库中添加一个名为filename的字段。 但是我无法获取上载文件的文件名。 有没有获得它的方法? 还是可以使用BufferedReader读取文件?

FileUploadDB.java

package com.process.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

@WebServlet("/fileuploaddb.html")
@MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;


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

private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";

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

    // gets values of text fields
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");

            InputStream inputStream = null; // input stream of the upload file

            // obtains the upload file part in this multipart request
            Part filePart = request.getPart("photo");
            if (filePart != null) {
                // prints out some information for debugging
                System.out.println(filePart.getName());
                System.out.println(filePart.getSize());
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
            }

            Connection conn = null; // connection to the database
            String message = null;  // message will be sent back to client

            try {

                // connects to the database
                //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                //DriverManager.getConnection(dbURL);
                //com.microsoft.sqlserver.jdbc.Driver

                Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
                if(conn!=null) {
                    System.out.println("Connection Successful!");
                } else {
                    System.out.println("Error in Connection");
                }
                // constructs SQL statement
                String sql = "INSERT INTO contact (firstname, lastname, photo) values (?, ?, ?)";
                PreparedStatement statement = conn.prepareStatement(sql);
                statement.setString(1, firstName);
                statement.setString(2, lastName);

                if (inputStream != null) {
                    // fetches input stream of the upload file for the blob column
                    statement.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));                     

                }

                // sends the statement to the database server
                int row = statement.executeUpdate();
                if (row > 0) {
                    message = "File uploaded and saved into database";
                }
            } catch (SQLException ex) {
                message = "ERROR: " + ex.getMessage();
                ex.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    // closes the database connection
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                // sets the message in request scope
                request.setAttribute("Message", message);

                // forwards to the message page
                         getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
            }
        }
        }

这是upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
    <h1>File Upload to Database Demo</h1>
    <form method="post" action="fileuploaddb.html" enctype="multipart/form-data">
        <table border="0">
            <tr>
                <td>First Name: </td>
                <td><input type="text" name="firstName" size="50"/></td>
            </tr>
            <tr>
                <td>Last Name: </td>
                <td><input type="text" name="lastName" size="50"/></td>
            </tr>
            <tr>
                <td>Portrait Photo: </td>
                <td><input type="file" name="photo" size="50"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Save">
                </td>
            </tr>
        </table>
    </form>
</center>
</body>
</html>


**This is the Message.jsp**

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
    <h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>

**在这部分上,System.out.println(filePart.getName()); 不会打印要上传的所选文件的文件名,但是会打印出“照片”一词。 哪个是

Part filePart = request.getPart("photo");

if (filePart != null) {
    // prints out some information for debugging

    System.out.println(filePart.getName());
    System.out.println(filePart.getSize());
    System.out.println(filePart.getContentType());

    // obtains input stream of the upload file
    inputStream = filePart.getInputStream();

}

将数据插入数据库没有麻烦,但是我无法获取上载文件的文件名。 有没有获得它的方法?

从Servlet API 3.1开始, Part接口提供了getSubmittedFileName()方法,该方法可以满足您的需求。

获取客户端指定的文件名

此类表示在multipart/form-data POST请求中收到的零件或表单项。


另外,您可以使用Apache提供的Commons Fileupload库 ,可以轻松地向Servlet和Web应用程序添加强大的,高性能的文件上传功能。

样例代码:

 List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);

 for(FileItem item : multiparts){
    if(!item.isFormField()){
        String name = new File(item.getName()).getName();

    }
 }

在这里这里找到完整的代码

使用以下方法

private String getFileName(Part p){
        String header=p.getHeader("content-disposition");
        String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1];  //getting filename

        return filename;
}

该片段是从我的博客采取这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM