我试图从phpMyAdmin数据库中删除文件。我在php中编写了一个与数据库交互的脚本,并通过输入文件ID号来删除特定文件(通过使用Web客户端验证)。但现在我想用http java客户端删除。但它不起作用。如何使用http java客户端删除文件。我下载了apache的外部jar文件。 :
以下是我使用Jswing删除文件的功能:
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==button1)
{
int reply = JOptionPane.showConfirmDialog(null, "Do you want to delete a file", "Delete File", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
//JOptionPane.showMessageDialog(null, "HELLO");
String[] options = new String[]{"id","Filename"};
int response = JOptionPane.showOptionDialog(null, "Message", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if(response == 0)
{
String userInput = (String)JOptionPane.showInputDialog(
null,
"Enter the file name",
"Input",
JOptionPane.PLAIN_MESSAGE,
null,
null,
null);
CloseableHttpClient httpClient = null;
String phpURL = "http://emysdomain.com/";
JavaHttpClient.deleteFile(httpClient, userInput, phpURL);
repaint();
//String phpUrl is my domain name.
//repaint to refresh the table. I think i'm wrong using repaint to refresh the table
}
这是我的http java客户端删除文件:
public static boolean deleteFile(CloseableHttpClient httpClient, String id, String uploadURL){
HttpPost httppost = null;
HttpEntity resEntity = null;
HttpResponse response = null;
httpClient = HttpClients.createDefault();
try {
httppost = new HttpPost(uploadURL+"delete.php");
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.addTextBody("id", id);
httppost.setEntity(multipartEntity.build());
response = httpClient.execute(httppost);
resEntity = response.getEntity();
if (resEntity != null)
EntityUtils.consume(resEntity);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode <= HttpStatus.SC_TEMPORARY_REDIRECT
&& statusCode >= HttpStatus.SC_OK) //SC_OK = 200
{
return true;
}
}
catch(Exception e) {
e.printStackTrace();
return false;
}
return false;
}
}
下面是我的php删除文件:
<?php
/**
*
*
*
*
*/
include 'db.php';
$con = mysqli_connect($host, $username, $password, $database);
$file_name = $_POST["id"];
if(isset($_POST["id"])){
$id = $_POST["id"];
$result = mysqli_query($con, "SELECT * FROM Files WHERE idFiles='$id'");
$row = mysqli_fetch_array($result);
$url = $row['url'];
unlink($url);
$query = "DELETE FROM Files WHERE idFiles='$id';";
mysqli_query($con,$query);
}
mysqli_close($con);
//redirect
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'webclient.php';
header("Location: http://$host$uri/$extra");
exit;