这是自己搭建的用来测试 Android多文件,不同类型上传 ,服务器php接收。
后端php 与java 接收文件是有点区别的,单独一个文件上传,没区别,但是多文件上传 Android端的一个坑,就是 name 字段
php 接收的是一个数组,Android端 只能builder.addFormDataPart("image[]")
Android 端注意点
使用的是okhttp3.4
builder.addFormDataPart("image[]") 红色字段
php端注意点
使用phpStudy 集成开发环境
修改 使用自己的ip来访问
1 修改 vhosts文件下
<VirtualHost *:80>
DocumentRoot "D:\phpstudy\PHPTutorial\WWW"
ServerName 192.168.42.214 //修改成你自己的IP
ServerAlias gohosts.com
<Directory "D:\phpstudy\PHPTutorial\WWW">
Options FollowSymLinks ExecCGI Indexes
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
</VirtualHost>修改hosts 文件
127.0.0.1 192.168.42.214//修改成你自己的IP
测试效果
php代码
<?php error_reporting(0); ini_set('date.timezone','Asia/Shanghai'); header('Content-type: application/json;charset=utf-8'); $array=$_FILES["image"]["name"]; if(empty($array)) die('{"status":0,"msg":"错误提交"}'); $dirpath = "./upload/"; if(!is_dir($dirPath)){ //目录不存在则创建目录 mkdir($dirPath,0777, true); } $count = count($array);//所有文件数 if($count<1) die('{"status":0,"msg":"错误提交"}');//没有提交的文件 $success = $failure = 0; for($i=0;$i<count($array);$i++){ $target_path=$dirpath.date('YmdHis').$_FILES["image"]["name"][$i]; if(move_uploaded_file($_FILES["image"]['tmp_name'][$i], $target_path) ) { $success++; $status=1; $mes="提交成功"; } else{ $status=0; $mes="提交失败"; $failure++; } } $arr['status'] = $status; $arr['msg'] = $mes; $arr['success'] = $success; $arr['failure'] = $failure; echo json_encode($arr,JSON_UNESCAPED_UNICODE);
Android 端代码
//准备数据 List<String> img = new ArrayList<>(); String path_1 = getCacheDir().getPath()+File.separator+"one.png"; String path_2 = getCacheDir().getPath()+File.separator+"three.png"; //String path_3 = getCacheDir().getPath()+File.separator+"two.png"; String path_3 = getCacheDir().getPath()+File.separator+"1.mp4"; String path_4 = getCacheDir().getPath()+File.separator+"h.txt"; img.add(path_1); img.add(path_2); img.add(path_3); img.add(path_4); String url="http://192.168.42.214/index.php";//修改为自己的主机ip UpLoadFile(url, img, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("上传失败",e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.e("上传成功",response.body().string()); } });
@TargetApi(Build.VERSION_CODES.O) public void UpLoadFile(String url, List<String> name, Callback callback){ OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.newCall(getRequest(url,name)).enqueue(callback); } @RequiresApi(api = Build.VERSION_CODES.O) private Request getRequest(String url, List<String> name) { Request build = new Request.Builder() .url(url) .post(getRequsetBody(name)) .build(); return build; }
@RequiresApi(api = Build.VERSION_CODES.O) private RequestBody getRequsetBody(List<String> name) { MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); for(int i=0;i<name.size();i++){ File file = new File( name.get(i)); String mimeType = getMimeType(file); builder.addFormDataPart("image[]",file.getPath(),RequestBody.create(MediaType.parse(mimeType),file)); } return builder.build(); }
private static String getSuffix(File file) { if (file == null || !file.exists() || file.isDirectory()) { return null; } String fileName = file.getName(); if (fileName.equals("") || fileName.endsWith(".")) { return null; } int index = fileName.lastIndexOf("."); if (index != -1) { return fileName.substring(index + 1).toLowerCase(Locale.US); } else { return null; } } public static String getMimeType(File file){ String suffix = getSuffix(file); if (suffix == null) { return "file/*"; } String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix); if (type != null || !type.isEmpty()) { return type; } return "file/*"; }