觸動精靈 下載,上傳文件

上傳文件:

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("執行完成")

與君共勉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章