安装插件
官网https://ionicframework.com/docs/native/file-transfer/
https://ionicframework.com/docs/native/file/
https://ionicframework.com/docs/native/file-chooser/
https://ionicframework.com/docs/native/file-opener/
java服务器编码
springmvc中要做如下配置,才能正常接收文件
官网https://ionicframework.com/docs/native/file-transfer/
https://ionicframework.com/docs/native/file/
https://ionicframework.com/docs/native/file-chooser/
https://ionicframework.com/docs/native/file-opener/
安装命令
▲ionic-native/file-chooser
ionic cordova plugin add cordova-plugin-filechooser
npm install --save @ionic-native/file-chooser
▲ionic-native/file-transfer
ionic cordova plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/file-transfer
▲ionic-native/file
ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file
▲ionic-native/file-opener
ionic cordova plugin add cordova-plugin-file-opener2
npm install --save @ionic-native/file-opener
*切记所有的插件要在app.Module.ts中的providers引用
ionic编码
▲html
<ion-content padding>
<button ion-button block color="danger" (click)="choose()">
选择文件
</button>
文件:<a>{{filePath}}</a>
<button ion-button block color="danger" (click)="upload()">
上传文件
</button>
进度:<a>{{loadingStatus}}</a>
<button ion-button block color="danger" (click)="download()">
下载文件
</button>
</ion-content>
▲ts
//导入
import { Component } from '@angular/core';
import { NavController,LoadingController,Loading } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
//构造
filePath : string;
loadingStatus : any;
private loading: Loading;
constructor(public navCtrl: NavController,
private loadingCtrl: LoadingController,
private fileChooser: FileChooser,
private fileTransfer:FileTransfer,
private file :File,
private fileOpener: FileOpener) {
this.filePath="";
}
// 选择文件
choose(){
this.fileChooser.open()
.then(uri => {
console.log(uri);
this.filePath=uri;
alert(this.filePath);
})
.catch(e => console.log(e));
}
// 上传文件
upload(){
if(this.filePath==""){
alert("请选择文件");
return;
}
const transfer: FileTransferObject = this.fileTransfer.create();
// 文件类型
let fileType=this.getFileType(this.filePath);
// 文件名
let fileName=this.getFileName(this.filePath);
let fileMimeType=this.getFileMimeType(fileType);
// FileUploadOptions
let options: FileUploadOptions = {
fileKey: 'file',
fileName: fileName,
mimeType: fileMimeType,
headers: {}
}
let loading = this.loadingCtrl.create({
spinner: 'hide',
content: '...'
});
// 服务器URL
var serverUrl='http://xxxxxxxxx/upload.do';
// 上传进度
transfer.onProgress(ProgressEvent=>{
if (ProgressEvent.lengthComputable) {
console.log(ProgressEvent.loaded / ProgressEvent.total);
this.loadingStatus=Number(Math.round((ProgressEvent.loaded / ProgressEvent.total)*100)).toFixed(2).toString() + "%";
if(!this.loading){//如果loading已经存在则不再打开
let loading = this.loadingCtrl.create({
content: this.loadingStatus
});
loading.present();
this.loading = loading;
setTimeout(() => {//延迟200毫秒可以避免嵌套请求loading重复打开和关闭
this.loading && this.loading.dismiss();
this.loading = null;
}, 50);
}
if (ProgressEvent.loaded > 99){
this.loading.dismiss();
}
} else {
this.loadingStatus=0;
}
} );
// 上传文件到服务器
transfer.upload(this.filePath, serverUrl, options,false)
.then((data) => {
// success
alert("success");
}, (err) => {
// error
alert(err.code);
})
}
// 从服务器下载文件
download() {
const transfer: FileTransferObject = this.fileTransfer.create();
const url = 'http://172.20.202.131:8083/smsc/ionic/sp101/download.do';
var fileName='?name=test.txt';
transfer.download(url+fileName, this.file.dataDirectory + 'test.txt').then((entry) => {
console.log('download complete: ' + entry.toURL());
this.fileOpener.open(entry.toURL(), 'text/plain')
.then(() => alert('File is opened'))
.catch(e => alert('Error openening file'));
}, (error) => {
// handle error
alert(error.code);
});
}
// 根据url获取文件类型
getFileType(fileUrl: string): string {
return fileUrl.substring(fileUrl.lastIndexOf('.') + 1, fileUrl.length).toLowerCase();
}
// 根据url获取文件名(包含文件类型)
getFileName(fileUrl: string): string {
return fileUrl.substring(fileUrl.lastIndexOf('/') + 1, fileUrl.length).toLowerCase();
}
文件的mimeType可参照
http://www.w3school.com.cn/media/media_mimeref.asp
http://tool.oschina.net/commons/
http://www.iana.org/assignments/media-types/media-types.xhtml
// 根据文件类型获取文件的mimeType
getFileMimeType(fileType: string): string {
let mimeType: string = '';
switch (fileType) {
case 'txt':
mimeType = 'text/plain';
break;
case 'docx':
mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'doc':
mimeType = 'application/msword';
break;
case 'pptx':
mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'ppt':
mimeType = 'application/vnd.ms-powerpoint';
break;
case 'xlsx':
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'xls':
mimeType = 'application/vnd.ms-excel';
break;
case 'zip':
mimeType = 'application/x-zip-compressed';
break;
case 'rar':
mimeType = 'application/octet-stream';
break;
case 'pdf':
mimeType = 'application/pdf';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
case 'png':
mimeType = 'image/png';
break;
default:
mimeType = 'application/' + fileType;
break;
}
return mimeType;
}
java服务器编码
springmvc中要做如下配置,才能正常接收文件
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="1048576000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
文件上传
@RequestMapping(value="/upload" ,method=RequestMethod.POST)
@ResponseBody
public Map<String, String> getFile(HttpServletRequest request,HttpServletResponse response,@RequestParam MultipartFile file){
response.setHeader("Access-Control-Allow-Origin", "*");
Map<String, String> userMap = new HashMap<String, String>();
userMap.put("msg", "成功");
//保存文件到临时目录
String savePath = "D:\\XXX\\server\\file\\"+ file.getOriginalFilename();
System.out.println(savePath);
File saveFile = new File(savePath);
try {
file.transferTo(saveFile);
} catch (IllegalStateException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//String fileName = file.g;
return userMap;
}
文件下载
@RequestMapping(value="/download")
@ResponseBody
public void downFile(HttpServletRequest request,HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "*");
try {
request.getSession().getServletContext().getRealPath("/");
System.out.println(request.getSession().getServletContext().getRealPath("/"));
request.setCharacterEncoding("UTF-8");
// 文件名
String name = request.getParameter("name");
// 设置响应类型(应用程序强制下载)
response.setContentType("application/force-download");
// 读取文件
String path = "D:\\XXX\\server\\file\\" + name;
InputStream in = new FileInputStream(path);
// 设置响应头,对文件进行url编码
name = URLEncoder.encode(name, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
response.setContentLength(in.available());
// 文件copy
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}