android上传下载

上传 移动端

public static void upload(String filePath, final SuperWebView superWebView) {
        String url="";                      //服务端负责接收数据的链接
        RequestParams params = new RequestParams();
        params.addBodyParameter("file", new File(filePath));
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

            public void onStart() {
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Toast.makeText(activity, "上传成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(activity, "上传失败", Toast.LENGTH_SHORT).show();
                ToolUtil.showShortTip(ToolUtil.activity, "上传失败!");
            }
        });
    }

上传 服务端

public ActionForward upload(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        try{
            String nowpath; //当前tomcat的bin目录的路径 如 D:/java/software/apache-tomcat-6.0.14/bin
            String tempdir;
            nowpath = System.getProperty("user.dir");
            tempdir = nowpath+"/temp";
            // 解析 request,判断是否有上传文件  
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
            if (isMultipart) {  
                // 创建磁盘工厂,利用构造器实现内存数据储存量和临时储存路径  
                File file = new File(tempdir);
                if(!file.exists() && !file.isDirectory()){
                    file.mkdir();
                }
                DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File(tempdir));  
                // 产生一新的文件上传处理程式  
                ServletFileUpload upload = new ServletFileUpload(factory);  
                 // 设置路径、文件名的字符集  
                /*upload.setHeaderEncoding("GBK");*/ 
                /*当文件名为汉字时 upload.setHeaderEncoding("GBK") 出现乱码 故改为utf-8*/
                upload.setHeaderEncoding("utf-8"); 
                // 设置允许用户上传文件大小,单位:字节  
                upload.setSizeMax(1024 * 1024 * 100);  
                // 解析请求,开始读取数据  
                // Iterator<FileItem> iter = (Iterator<FileItem>) upload.getItemIterator(request);  
                // 得到所有的表单域,它们目前都被当作FileItem  
                List<FileItem> fileItems = upload.parseRequest(request);  
                // 依次处理请求  
                Iterator<FileItem> iter = fileItems.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && StringUtils.isNotEmpty(item.getName().trim())) {  
                        // 如果item是文件上传表单域  
                        // 获得文件名及路径  
                        String fileName = item.getName();  
                        if (fileName != null) {  
                            // 如果文件存在则上传  
                            InputStream in = item.getInputStream();
                            byte[] imageByte = new byte[(int) in.available()];
                            in.read(imageByte);
                            in.close();
                            String realPath = request.getRealPath("androidFile")+"/"+fileName;
                            File file2 = new File(realPath);
                            if (!file2.exists()){
                                File vDirPath = file2.getParentFile(); // new
                                vDirPath.mkdirs();
                                FileOutputStream fileOut = new FileOutputStream(file2);
                                fileOut.write(imageByte);
                                fileOut.close();
                            }
                        }  
                    }  
                }  
            } 
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

下载 手机端

public static void download(final SuperWebView superWebView,String severPath,String androidPath,String fileName){
            HttpUtils http = new HttpUtils();
            RequestParams requestParams = new RequestParams();
            String appURL ="";                                  //服务端负责下载类 需要传递serverPath和fileName
            File file2 = new File(androidPath);
            if (!file2.exists()){
                http.download(appURL,
                        androidPath,
                        requestParams,
                        true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                        false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
                        new RequestCallBack<File>() {
                            public void onStart() {
                                progressDialog = new ProgressDialog(superWebView.getContext());
                                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                progressDialog.setTitle("["+downLoadName+"]下载中...");
                                progressDialog.show();
                            }
                            public void onLoading(long total, long current, boolean isUploading) {
                                progressDialog.setMax((int)total);
                                progressDialog.setProgress((int)current);
                            }
                            public void onSuccess(ResponseInfo<File> responseInfo) {
                                progressDialog.hide();
                            }
                            public void onFailure(HttpException error, String msg) {
                                ToolUtil.showShortTip((Activity) superWebView.getContext(),msg);
                            }
                        });
            }
    }

下载 电脑端

public ActionForward download(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        String curFile = WebProcess.getParameter(request, "fileName");
        String filePath = WebProcess.getParameter(request, "serverPath");
        try{
            filePath=new String(filePath.getBytes("iso8859-1"),"utf-8");
            curV=new String(curV.getBytes("iso8859-1"),"utf-8");
        }catch(Exception e){
            e.printStackTrace();
        }
        response.setContentType("application/octet-stream");
        response.setHeader("charset", "UTF-8");
        response.setHeader("Content-Disposition", "filename="+curFile);
        //得到文件大小   
        //读数据 
        byte data[] = null;
        FileInputStream hFile = null;
        try {
            hFile = new FileInputStream(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            OutputStream out = response.getOutputStream();
            int i=hFile.available(); 
            response.addHeader("Content-Length", i+"");
            byte[] buf = new byte[i];
            hFile.read(buf);
            out.write(buf);
            hFile.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
        }
        return null;
    }
Android 上传文件至服务器和下载文件至本地,亲测有效,只需传入相关参数即可。/** * android上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(Map<String,String>params,File file, String RequestURL) { String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { Log.i(TAG, "====file is"+file); /** * 当文件不为空,把文件包装并且上传 */ OutputStream outputSteam = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); /************************上传表单的一些设置信息***********************************/ if (params != null) for (String key : params.keySet()) { sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n"); sb.append("\r\n"); sb.append(params.get(key) + "\r\n"); } /************************上传文件的一些设置信息***********************************/ sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值