记录一个可以上传图片的代码

 

上传图片是一种基本操作,网络框架也很好用,这里采用一种最基本的方式,记录一下以后可能用得到

 

 

package com.example.appupload;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.Button;

public class MainActivity extends Activity {
	
	Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.myButton);
		
		//给布局设置监听器,当然也可以没有这部分
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//文件路径,真实的上传这部分往往是从相册选取,或者通过拍照得到,也许还有裁剪,如果没有就找一张图片,把路径放在这里
				String url = "/storage/emulated/0/image2.jpg";
				
				//上传文件的接口
				String[] datas = {url, "http://1.appprogram.sinaapp.com/upload1.php"};
				
				//这里是通过异步任务上传,为基础起见,没有用框架,最好要加上有无网络等的判断
				FileUploadTask task = new FileUploadTask();
				task.execute(datas);
			}
		});
	}
	
	class FileUploadTask extends AsyncTask<String, Integer, Void> {   
		   
		//显示上传进度的进度条
	     private ProgressDialog dialog = null;
	     //网络访问的connection
	     HttpURLConnection connection = null;   
	     //上传的流
	     DataOutputStream outputStream = null;   
	     DataInputStream inputStream = null;   
	     @Override   
	     protected void onPreExecute() {  
	    	 
	    	 //初始化进度条的逻辑
	         dialog = new ProgressDialog(MainActivity.this);   
	         dialog.setMessage("正在上传...");   
	         dialog.setIndeterminate(false);   
	         dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   
	         dialog.setProgress(0);   
	         dialog.show();   
	     }   
	     @Override   
	     protected Void doInBackground(String... arg) {   
	       //要上传的文件    
	         String pathToOurFile =arg[0];   
	         //上传接口地址   
	         String urlServer = arg[1];   
	         String lineEnd = "\r\n";   
	         String twoHyphens = "--";   
	         String boundary = "*****";   
	    
	         File uploadFile = new File(pathToOurFile); 
	         //拿到上传文件的大小用于计算
	         long totalSize = uploadFile.length();     
	     
	     
	         long length = 0;   
	         int progress;   
	         int bytesRead, bytesAvailable, bufferSize;   
	         byte[] buffer;   
	         
	         //设置最大缓存
	         int maxBufferSize = 2560 * 10240;// 25600KB    
	         try {   
	             FileInputStream fileInputStream = new FileInputStream(new File(   
	                     pathToOurFile));   
	             URL url = new URL(urlServer);   
	             connection = (HttpURLConnection) url.openConnection();   
	             // 设置输出流大小    
	             connection.setChunkedStreamingMode(2560 * 10240);// 25600KB    
	             // 设置允许输入输出   
	             connection.setDoInput(true);   
	             connection.setDoOutput(true);   
	             connection.setUseCaches(false);   
	             // 开启Post方法   
	             connection.setRequestMethod("POST");   
	             //设置保持连接
	             connection.setRequestProperty("Connection", "Keep-Alive");   
	             //报文格式
	             connection.setRequestProperty("Charset", "UTF-8");   
	             connection.setRequestProperty("Content-Type",   
	                     "multipart/form-data;boundary=" + boundary);   
	             outputStream = new DataOutputStream(   
	                     connection.getOutputStream());   
	             outputStream.writeBytes(twoHyphens + boundary + lineEnd);   
	             outputStream   
	                     .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""   
	                             + pathToOurFile + "\"" + lineEnd);   
	             outputStream.writeBytes(lineEnd);   
	             bytesAvailable = fileInputStream.available();   
	             bufferSize = Math.min(bytesAvailable, maxBufferSize);   
	             buffer = new byte[bufferSize];   
	             // Read file    
	             bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
	             while (bytesRead > 0) {   
	                 outputStream.write(buffer, 0, bufferSize);   
	                 length += bufferSize;   
	                 progress = (int) ((length * 100) / totalSize);   
	                 publishProgress(progress);   
	                 bytesAvailable = fileInputStream.available();   
	                 bufferSize = Math.min(bytesAvailable, maxBufferSize);   
	                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
	             }   
	             outputStream.writeBytes(lineEnd);   
	             outputStream.writeBytes(twoHyphens + boundary + twoHyphens   
	                     + lineEnd);   
	             publishProgress(100);   
	             // 回传信息    
	             int serverResponseCode = connection.getResponseCode();   
	             String serverResponseMessage = connection.getResponseMessage();   
	             fileInputStream.close();   
	             outputStream.flush();   
	             outputStream.close();   
	         } catch (Exception ex) {   
	         }   
	         return null;   
	     }   
	     @Override   
	     protected void onProgressUpdate(Integer... progress) {   
	         dialog.setProgress(progress[0]);   
	     }   
	     @Override   
	     protected void onPostExecute(Void result) {   
	         try {   
	             dialog.dismiss();   
	         } catch (Exception e) {   
	         }   
	     }   
	 }   
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值