zoukankan      html  css  js  c++  java
  • Android -- 文件上传到服务器

    1. 文件上传的两种方式

    (1) HttpClient

    (2)AsyncHttpClient (开源框架: https://github.com/loopj/android-async-http

    示例代码(2)最简单

    public void upload(View v){
    		String path = et_path.getText().toString().trim();
    		File file = new File(path);
    		String uri = "http://192.168.1.100:8080/TestLogin/servlet/UploadFile";
    		if(file.exists() && file.length()>0){
    			AsyncHttpClient client = new AsyncHttpClient();
    			RequestParams params = new RequestParams();
    			try {
    				params.put("profile_picture", file);
    			} catch (FileNotFoundException e) {			
    				e.printStackTrace();
    			}
    			client.post(uri, params, new AsyncHttpResponseHandler(){
    
    				@Override				
    				public void onFailure(Throwable error, String content) {
    					Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
    				}
    
    				@Override
    				public void onSuccess(String content) {
    					Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
    				}
    				
    			});					
    		}else{
    			Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
    		}
    	}


    示例代码(1)

    public void upload(View viwe){
    		HttpClient client = new HttpClient();
    		 PostMethod filePost = new PostMethod("http://192.168.1.100:8080/web/UploadServlet");;
        	try {
    			String path = et_path.getText().toString().trim();
    			File file = new File(path);
    			if(file.exists()&&file.length()>0){
    				Part[] parts = {new StringPart("nameaaaa", "valueaaa"), 
    					  new StringPart("namebbb", "valuebbb"), 
    					  new FilePart("pic", new File(file.getAbsolutePath()))};
    			  filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    			  client.getHttpConnectionManager().getParams()
    			      .setConnectionTimeout(5000);
    			  int status = client.executeMethod(filePost);
    			  if(status ==200){
    				  Toast.makeText(this, "上传成功", 1).show();
    			  }else{
    				  Toast.makeText(this, "上传失败", 1).show();
    			  }
    			  
    			}
    			else{
    				Toast.makeText(this, "上传的文件不存在", 0).show();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			filePost.releaseConnection();
    		}
        	
        }


     

  • 相关阅读:
    将来要干啥
    选新技术考虑点
    hdfs 创建一个新用户
    linux下实现mysql数据库定时备份
    PostgreSQL的安装和卸载,远程连接
    PostgreSQL语法
    【NiFi系列】1-基本介绍
    大数据相关资源网址
    MySQL主从复制配置
    MySQL设置免密登录
  • 原文地址:https://www.cnblogs.com/xj626852095/p/3647974.html
Copyright © 2011-2022 走看看