获取手机端上传的文件流
平台提供了专门上传的API-$file.upload()或summer.upload(),这是针对单个文件的上传操作,操作中不能携带参数,此方法做多个文件上传只能通过循环实现。
如果是一个请求中有参数又有文件,可以用以下方法实现。
在callAction中携带上传文件,代码分两部分
1、端上通过callAction的mauploadpath参数将图片携带到MA
DSL工程:
$service.writeConfig({
"host" : "10.2.112.58",//向configure中写入host键值
"port" : "8085"//向configure中写入port键值
});
$service.callAction({
viewid: "com.yonyou.TestFileUploadController",//部署在MA上的Controller的包名
action: "testUpload",//后台Controller的方法名,
params: {a:1, b:2},//自定义参数,json格式
mauploadpath : "文件本地路径",
autoDataBinding: false,//请求回来的数据会在Context中,是否进行数据绑定,默认不绑定
contextmapping: "fieldPath",//将返回结果映射到指定的Context字段上,支持fieldName和xx.xxx.fieldName字段全路径,如未指定contextmapping则替换整个Context
callback: "uploadCallBack()",//请求成功后回调js方法
error: "uploadErrCallBack()"//请求失败回调的js方法
})
Summer工程:
summer.writeConfig({
"host" : "10.2.112.58",//向configure中写入host键值
"port" : "8085"//向configure中写入port键值
});
summer.callAction({
viewid: "com.yonyou.TestFileUploadController",//部署在MA上的Controller的包名
action: "testUpload",//后台Controller的方法名,
params: {a:1, b:2},//自定义参数,json格式
mauploadpath : "文件本地路径",
callback: "uploadCallBack()",//请求成功后回调js方法
error: "uploadErrCallBack()"//请求失败回调的js方法
})
2、MA通过this.getData(UPLOAD_FILE)获取到文件进行后续操作,Controller类需要继承UMCommonController
public class ListTest extends UMCommonController {
public String upload(String test) throws FileUploadException, IOException {
Object inObj = getData(UPLOAD_FILE);
Object filename = getData(UPLOAD_FILE_NAME);
if (inObj != null && filename != null) {
InputStream in = (InputStream) inObj;
String value = filename.toString();
int start = value.lastIndexOf("/");
String fileName = value.substring(start + 1);
String saveName = fileName;
File file = new File("D:\", saveName);
if (!file.exists()) {
file.createNewFile();
}
OutputStream out = null;
try {
out = new FileOutputStream(file);
int length = 0;
byte[] buf = new byte[1024];
while ((length = in.read(buf)) != -1) {
out.write(buf, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
return "{a:b}";
}
}
说明
多个文件批量上传时需要mauploadpath参数中的多个文件用”,”分开;然后MA在获取时this.getData()参数为UPLOAD_MULTI_FILE,data此时为多个文件的二进制流Map。
还有另一种方法是通过$file.upload或summer.upload()方法上传,然后通过key在Controller中获取文件,再进行后续操作;这种方法会在MA上保存一份文件,不适用文件终点非MA的需求。
注意
不管是使用callAction,还是使用upload上传文件都需要勾选上传(upload)插件,方法如下:
文档更新时间: 2018-04-25 10:34