直入主题,accept接收文件格式可以是简化的文件类型或是完整的的文件类型,安卓各个版本系统的api存在差异,因此根据实际应用情况,比如上传文件是单选还是多选,最终也要结合系统支持的情况调试。
<input type="file" name="files[]" @change="fileChange($event)" accept=".doc,.docx,.ppt,.pdf,.xls,.xlsx"/>
<input type="file" name="files[]" multiple @change="fileChange($event)" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/pdf">
实际像Microsoft旗下的2003版本、2007版本以及最新的存在两种文件格式(比如.doc、.docx),考虑到wps会不会自行定义格式的情况。需要确认文件内容
移动端需求涉及上传文件,前期功能研发都是在PC端google chrome上调试,所以并没有发现文件不能上传问题。发布到开发库时发现android设备选择文件时没有换起系统文件管理器,研究了一番以为type="file"不支持,后面在iOS设备上验证是正常的。因为之前是android 开发者,所以猜想是不是系统有什么限制。之前公司产品都是图片的上传,所以系统版本兼容也都是处理webview.setWebChromeClient()里的openFileChooser/onShowFileChooser方法。
在自己app中的专属webview activity页面中,添加关键代码片段(这里只是引导处理的方案入口,实际需要对各系统进行适配--特别是近两年关注的隐私问题,对存储的适配):
private ValueCallback<Uri> mFileCallBack;
public ValueCallback<Uri[]> mFileCallBackList;
public static final int REQUEST_SELECT_FILE = 2022;
webview.setWebChromeClient(new WebChromeClient() {
// 5.0+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (mFileCallBackList!= null) {
mFileCallBackList.onReceiveValue(null);
mFileCallBackList= null;
}
mFileCallBackList= filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {//文件选择错误
uploadMessage = null;
return false;
}
return true;
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
}