如何在Java Servlet中实现此PHP代码


How can I implement this PHP code in Java Servlet

我试图通过拖放界面上传图像,我在这里得到了JavaScript代码,但服务器端代码是用PHP实现的,如下所示(我修改了它,将图像插入数据库):

<?php
//Connect to database
mysql_connect("localhost", "root", "something-strange") or die(mysql_error());
mysql_select_db("business_clax") or die(mysql_error());
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
if(!isset($file))
{
    echo "Please select an image.";
}
//This is the line of code I really want in Java
$image = addslashes(file_get_contents($file)); //SQL Injection defence!
$image_name = addslashes($name);
$sql = "UPDATE `adverts` SET `photos` = '{$image}' WHERE `id` = '1'";
if (!mysql_query($sql)) { // Error handling
    echo "Something went wrong! :(";
}
?>

上面的代码运行得很好,但我需要用Java来实现。我试图在Java Servlet中实现上面的代码,但我不知道如何在Java中实现file_get_contents($file)addslashes(file_get_contents($file));函数,我认为必须有一个等效的方法。求你了,我需要帮助。谢谢

要获得文件的byte[]表示形式,我会查看Apache FileUtils库,特别是org.apache.commons.io.FileUtils.readFileToByteArray(java.io.File file)方法。

要获得文件的String表示形式,请使用org.apache.commons.io.FileUtils.readFileToString(java.io.File file)(您还需要了解java文件)

此外,java.sql.PreparedStatement对象可以防止SQL注入攻击。