我创建了用于将文件上传到MySQL数据库的servlet:
@WebServlet("/UploadFileController") @MultipartConfig(maxFileSize = 16177215)
public class UploadFileController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Random rand = new Random();
int n = rand.nextInt(9999) + 1;
String idTemp=(String.valueOf(n));
String title=(request.getParameter("title"));
Part filePart = request.getPart("file_uploaded");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
Db_Connection dbconn=new Db_Connection();
Connection conn= dbconn.Connection();
String sql = "INSERT INTO books (id, title, author, keywords, publication_year, filename, MIME, file) values (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, idTemp);
statement.setString(2, title);
statement.setString(3, "Goran");
statement.setString(4, "Analisis");
statement.setString(5, "1995");
statement.setString(6, "OrgFileName");
statement.setString(7, "pdf");
if (inputStream != null)
{
statement.setBinaryStream(8, inputStream, (int) filePart.getSize());
}
int row = statement.executeUpdate();
if (row > 0)
{
out.println("File uploaded!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("upload_form.jsp");
rs.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("upload_form.jsp");
rs.include(request, response);
}
}catch(Exception e){e.printStackTrace();}
}
}
现在,我在数据库中手动输入了一些字符串,而不是上载文件的真实元数据。 我正在尝试通过TIKA获取元数据。
public class MetadataViewer {
public static void main(final String[] args) throws IOException, TikaException {
//Assume that boy.jpg is in your current directory
File file = new File("C:/Users/goran/Desktop/zadatak_grupa_B.pdf");
//Parser method parameters
Parser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(file);
ParseContext context = new ParseContext();
try {
parser.parse(inputstream, handler, metadata, context);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(handler.toString());
//getting the list of all meta data elements
String[] metadataNames = metadata.names();
for(String name : metadataNames) {
System.out.println(name + ": " + metadata.get(name));
}
}
}
很明显,目前该类目前仅可用于以下特殊文件,例如:File file = new File("C:/Users/goran/Desktop/zadatak_grupa_B.pdf");
,并在控制台中写入元数据。
如何读取上传文件的元数据并将其输入数据库?