上传文件:
function uploadFile(filePath,url)
os.execute("curl -F \"file=@"..filePath.."\" "..url)
end
下载文件:
function downloadFile(filePath,url)
os.execute("curl -o " .. filePath .. " " .. url)
end
上面的方法只是调用了linux本地的方法,另外,curl这个命令像这样直接用是无法进行https的请求的,好像需要证书什么的,没仔细研究.curl这个命令的功能还挺强大的,有兴趣可以去百度学习下.
2017-12-28
关于上传
之前使用ios8越狱之后这个命令可以使用,但是换到ios9上之后curl这个命令变得无法使用,但是我使用base64进行编码到服务器解码又有问题,java和lua的base64编码都不一样,搞了很长时间都没搞好,今天上午解决了这一个问题
require("TSLib")
require("sz")
snapshot("sm.png", 200,230,600,500)
local file=io.open("/private/var/mobile/Media/TouchSprite/res/sm.png")
local msg="";
if file then
msg=file:read("*a");
file:close()
end
tomcatUrl="http://192.168.1.117:8080/yh/"
httpPost(tomcatUrl.."UploadTest?name=sm&id=11",msg)
nLog("执行完成")
最麻烦的是,lua没有字节和字符之分,或者是有但是分界线并不明显,就像这个file:read()这个方法如果读取txt就会返回string如果读取图片返回的好像就是字节,总之,也算是我的理解不够吧.下面放上服务器接收的代码:
public class UploadTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("UTF-8");
upload(req, "C:\\c.png");
String name = StringUtil.removeNull(req.getParameter("name"));
Log.d(name);
String id = StringUtil.removeNull(req.getParameter("id"));
Log.d(id);
}
/**
* 接收上传的文件
*
* @param req
* @param path
* @throws IOException
*/
public void upload(HttpServletRequest req, String path) {
try {
InputStream inputStream = req.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
byte[] bs = new byte[1024];
int l = 0;
while ((l = inputStream.read(bs)) != -1) {
fileOutputStream.write(bs, 0, l);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器注意一点,如果在url中有参数上传需要先将body中的流读取出来,然后再去获取url中的参数,否则,读取到的流将会是空的.
关于下载
function download(path,url)
delFile(path)
local result=httpGet(url)
if result~=false then
local file=io.open(path,"w")
if file then
file:write(result)
file:close()
end
end
end
download("/private/var/mobile/Media/TouchSprite/res/baidu.png","https://www.baidu.com/img/bd_logo1.png")
nLog("执行完成")
与君共勉