我正在试图弄清楚如何更改我要上传的文件的名称。
我真的更喜欢在将其上传到服务器之前更改它的名称
这是客户端(Android)端的上传方法 -
private void doFileUpload(){
File file1 = new File(pathofFile);
String urlString = "http://12.8.1.10/uploads/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
如果可以在客户端进行 - 请尝试具体说明如何操作。
如果不可能,唯一的选择是在服务器端执行此操作, 所以我添加了PHP代码 - 所以你可以解释我需要改变的地方,谢谢
Php代码 -
$target_path1 = "uploads/";
$target_path1 = $target_path1 . basename( $_FILES['uploadedfile1']['name']);
if(move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1)) {
echo "The first file ". basename( $_FILES['uploadedfile1']['name']).
" has been uploaded.";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile1']['name']);
echo "target_path: " .$target_path1;
}
答案 0 :(得分:1)
在目标路径中,您可以在此处更改名称
$fileName = $_FILES["uploadedfile1"]["name"];
$ext = "." . end(explode(".", $fileName));
$target_path1 = "uploads/";
$target_path1 = $target_path1 . $name_of_file_here . $ext;
if(move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1)) {
echo "The first file ". basename( $_FILES['uploadedfile1']['name'])." has been uploaded.";
//rest of code here....
另外作为旁注,如果您希望自己的文件名来自Android,则必须使用您希望的名称发送其他帖子数据,并将$name_of_file_here
设置为该变量。
$target_path1
应与“ uploads / myPic.jpg ”类似地阅读