APP前后台文件与图片传输

来源:互联网 发布:淘宝围巾店铺介绍 编辑:程序博客网 时间:2024/05/17 09:44

     刚做APP不久,做到文件传输的时候想了很多的方法都不是很理想,在同事的建议下采用Base64 的编码解码方式,这样方式确实蛮好的,也支持断点操作,且安全,只要页面和后台的编码和解码方式统一即可。在路径返回上也做了处理,是在服务器的路径下建一个文件夹保存用户上传的文件。贴上代码:

private String decode(String file) throws IOException{String fileExt = "";fileExt = file.substring(file.lastIndexOf(".")).toLowerCase();byte[] byteDatas = Base64.decode(file.substring(0, file.lastIndexOf(".")));String str = ServletActionContext.getServletContext().getRealPath("/") + "userPic/";String saveUrl = request().getContextPath() + "/userPic/";        File saveDirFile = new File(str);        if (!saveDirFile.exists()) {        saveDirFile.mkdirs();        }                String newFileName = FileUtils.getFileName()+ fileExt ; File ret = null;          BufferedOutputStream stream = null;          try {              ret = new File(str+newFileName);              FileOutputStream fstream = new FileOutputStream(ret);              stream = new BufferedOutputStream(fstream);              stream.write(byteDatas);} catch (IOException e) {e.printStackTrace();}finally{stream.close();}return saveUrl + newFileName;}

       最近又遇到了个问题base64传文件时,文件不能过大,之后又选择了另外一种方式解决:将APP端的文件以File对象传输,java后台也以File对象来接收保存,贴上代码:

// 上传文件域private File frequency_path;

/** * 获取app端上传的文件 * @return * @throws Exception */public String uploadFile() throws Exception {String filePath = ServletActionContext.getServletContext().getRealPath("/")+ "userVideo/";String saveUrl = request().getContextPath() + "/" + "userVideo" + "/";File mf = new File(filePath);if (!mf.exists()) {mf.mkdirs();}String fileName = FileUtils.getFileName() + ".mp3";FileOutputStream fos = null;FileInputStream fis = null;try {System.out.println("获取Android端传过来的普通信息:");System.out.println("文件存放目录: " + filePath);System.out.println("文件名称: " + fileName);System.out.println("文件大小: " + frequency_path == null ? 0: frequency_path.length());File outFile = new File(filePath + File.separator + fileName);fos = new FileOutputStream(outFile);fis = new FileInputStream(getFrequency_path());byte[] buffer = new byte[1024];int len = 0;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}System.out.println("文件上传成功");} catch (Exception e) {System.out.println("文件上传失败");e.printStackTrace();} finally {if (fos != null) {fos.close();}if (fis != null) {fis.close();}}return saveUrl + fileName;}



0 0
原创粉丝点击