java 安卓上传文件

1 ftp协议上传文件(需要有文件服务器)

1.1上传文件
 /**
     * 上传文件(可供Action/Controller层使用)
     * @param hostname FTP服务器地址
     * @param port  FTP服务器端口号
     * @param username  FTP登录帐号
     * @param password  FTP登录密码
     * @param pathname  FTP服务器保存目录
     * @param fileName  上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile (String hostname, int port, String username, String password, String pathname,
                                      String fileName, InputStream inputStream)
    {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding ("UTF-8");
        try
        {
            ftpClient.connect (hostname, port);
            ftpClient.login (username, password);
            int replyCode = ftpClient.getReplyCode ();
            if (!FTPReply.isPositiveCompletion (replyCode))
            {
                Log.e("tag",replyCode+"return");
                return flag;
            }

            ftpClient.setFileType (FTPClient.BINARY_FILE_TYPE);
            ftpClient.makeDirectory (pathname);
            ftpClient.changeWorkingDirectory (pathname);
            ftpClient.storeFile (fileName, inputStream);
            inputStream.close ();
            ftpClient.logout ();
            flag = true;
        }
        catch (Exception e)
        {
            Log.e("uploadError","upload ftp file error : "+e.toString());
        }
        finally
        {
            Log.e("tag","finally");
            if (ftpClient.isConnected ())
            {
                Log.e("tag","ftpClient.isConnected");
                try
                {
                    ftpClient.disconnect ();
                    Log.e("tag","ftpClient.disconnect");
                }
                catch (IOException e)
                {
                    Log.e("uploadError","close ftp connect  : "+e.toString());
                }
            }
        }
        return flag;
    }
1.2 下载文件
 
    /**
     * 下载文件
     * @param hostname FTP服务器地址
     * @param port FTP服务器端口号
     * @param username FTP登录帐号
     * @param password FTP登录密码
     * @param pathname FTP服务器文件目录
     * @param filename 文件名称
     * @param localpath 下载后的文件路径
     * @return
     */
    public static boolean downloadFile (String hostname, int port, String username, String password, String pathname,
        String filename, OutputStream out)
    {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient ();
        try
        {
        	ftpClient.setConnectTimeout(1000*10);
            //连接FTP服务器
            ftpClient.connect (hostname, port);
            //登录FTP服务器
            ftpClient.login (username, password);
            ftpClient.setControlEncoding ("UTF-8"); // 设置字符编码
            //验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode ();
            if (!FTPReply.isPositiveCompletion (replyCode))
            {
                LOGGER.info ("login ftp for download file fail.");
                return flag;
            }
            
            ftpClient.setKeepAlive(true);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
            //切换FTP目录
            ftpClient.changeWorkingDirectory (pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles ();
            for (FTPFile file : ftpFiles)
            {
                if (filename.equalsIgnoreCase (file.getName ()))
                {
                    ftpClient.retrieveFile (file.getName (), out);
                    out.flush ();
                    out.close ();
                    break;
                }
            }
            
            flag = true;
        }
        catch (Exception e)
        {
            LOGGER.error ("download file error.", e);
        }
        finally
        {
            if (ftpClient.isConnected ())
            {
                try
                {
                    ftpClient.logout ();
                }
                catch (IOException e)
                {
                    LOGGER.error ("close connection for download file error.", e);
                }
            }
            
            if (null != out)
            {
                try
                {
                    out.close ();
                }
                catch (IOException e)
                {
                    LOGGER.error ("close outputStream for download file error.", e);
                }
            }
        }
        return flag;
    }

1.3删除文件
/**
     * 删除文件
     * @param hostname FTP服务器地址
     * @param port FTP服务器端口号
     * @param username FTP登录帐号
     * @param password FTP登录密码
     * @param pathname FTP服务器保存目录
     * @param filename 要删除的文件名称
     * @return
     */
    public static boolean deleteFile (String hostname, int port, String username, String password, String pathname,
        String filename)
    {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient ();
        try
        {
            //连接FTP服务器
            ftpClient.connect (hostname, port);
            //登录FTP服务器
            ftpClient.login (username, password);
            //验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode ();
            if (!FTPReply.isPositiveCompletion (replyCode))
            {
                LOGGER.info ("login ftp delete ftp file fail.");
                return flag;
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory (pathname);
            ftpClient.dele (filename);
            ftpClient.logout ();
            flag = true;
        }
        catch (Exception e)
        {
            LOGGER.error ("delete ftp file error.", e);
        }
        finally
        {
            if (ftpClient.isConnected ())
            {
                try
                {
                    ftpClient.logout ();
                }
                catch (IOException e)
                {
                    LOGGER.error ("close connection for delete ftp file error.", e);
                }
            }
        }
        return flag;
    }

2.http post 上传文件

安卓采用 retrofit+okhttp 
声明接口:
 @Multipart
    @POST("File/Upload")
    Call upload(
            @Part("description") RequestBody description,
                              @Part MultipartBody.Part file);
上传部分的核心代码
 //构建body
            File file = new File(filePath);
            if(!file.exists()) {
               Toast.makeText(ac, "文件不存在", Toast.LENGTH_SHORT).show();
            }

            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);

            String descriptionString = "This is a description";
            RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);


            Call call = httpApi.upload(description,body);

服务端接收的代码
    @RequestMapping ("/Upload")
    public void upload (HttpServletRequest request, HttpServletResponse response)   { 
        try
        {
            /**
             * 测试数据
             */
            //String hostname = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPHOST");//"192.168.80.11";
        	String hostname = "192.168.80.11";
            int port = Integer.parseInt ((String) redisCacheUtil.getDataFromRedis ("Collection_FTPPORT"));
            String username = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPUSERNAME");
            String password = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPPASSWORD");
            password = AesKeyUtils.decrypt (password.trim (), PropertiesReader.getUserPwdKey ());
          
            //String filename = (String) map.get("filename");//filename
            
            MultipartHttpServletRequest mkRequest = (MultipartHttpServletRequest )request;
            MultipartFile file = mkRequest.getFile("aFile");
            String filename = file.getOriginalFilename();
            String pathname ="";
            if(!filename.contains("TP") && !filename.contains("SN")) {
            	pathname = "/ftpdir/ftpdir/App";
            }else{
            	pathname = "/ftpdir/custDocument";
            }
           
            System.out.println(filename);
            InputStream in = file.getInputStream();
            boolean uploadFile = FtpUtils.uploadFile (hostname, port, username, password, pathname, filename, in);
            response.addHeader("result", uploadFile+"");
            
        }
        catch (IOException e)
        {
            LOGGER.error ("upload error");
        } 
    }
    
这里调取ftp的方法,存取到ftp文件服务器中;如果不乣ftp服务器,则直接处理
 InputStream in = file.getInputStream();
将输入流读取到文件中,即可.

服务端下载的代码
    @RequestMapping ("/Download")
    public void download (HttpServletRequest request, HttpServletResponse response)
    {
        
        try
        {
            //String hostname = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPHOST");//"192.168.80.11";
            String hostname = "192.168.80.11";
            int port = Integer.parseInt ((String) redisCacheUtil.getDataFromRedis ("Collection_FTPPORT"));
            String username = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPUSERNAME");
            String password = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPPASSWORD");
            password = AesKeyUtils.decrypt (password.trim (), PropertiesReader.getUserPwdKey ());
            Map map = HttpToMap(request);
            String pathname = request.getParameter("pathname");
            String filename = request.getParameter("filename");
//          String pathname = (String) map.get("pathname");//"/ftpdir/ftpdir/App
//            String filename = (String) map.get("filename");//MOBILE_WORK.apk
            
            //导出文件名称
            response.reset ();
            response.setContentType ("application/audio/x-wav;charset=UTF-8");
            response.setHeader ("Content-disposition", "attachment;filename=" + filename);
            
            OutputStream out = response.getOutputStream ();
            FtpUtils.downloadFile (hostname, port, username, password, pathname, filename, out);
            
        }
        catch (IOException e)
        {
            LOGGER.error ("down error");
        }
        
    }



服务端删除文件的代码:
 @RequestMapping ("/Delete")
    @ResponseBody  
    public String  delete (HttpServletRequest request)   {  
        try
        {
            //String hostname = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPHOST");//"192.168.80.11";
            String hostname ="192.168.80.11";
            int port = Integer.parseInt ((String) redisCacheUtil.getDataFromRedis ("Collection_FTPPORT"));
            String username = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPUSERNAME");
            String password = (String) redisCacheUtil.getDataFromRedis ("Collection_FTPPASSWORD");
            password = AesKeyUtils.decrypt (password.trim (), PropertiesReader.getUserPwdKey ());
            //String pathname =(String) redisCacheUtil.getDataFromRedis ("APP_PATH"); // ;
            String pathname ="/ftpdir/custDocument";
            Map map = HttpToMap(request);
            String filename = (String) map.get("filename");
            
            boolean uploadFile = FtpUtils.deleteFile(hostname, port, username, password, pathname, filename);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result",uploadFile+"");
            return jsonObject.toJSONString();
        }
        catch (IOException e)
        {
            LOGGER.error ("upload error");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result",false+"");
            return jsonObject.toJSONString();
        }
       
    }


同理,下载和删除可直接绕过ftp,直接操作服务器固定文件夹下的文件
    

你可能感兴趣的:(java 安卓上传文件)