网络编程---Android开源组件(Async-http)实现文件上传

今天学习了使用开源组件(Android-ansync-http)实现文件上传。这是是组件的github链接 https://github.com/loopj/android-async-http

使用androidStudio,只需在Gradle中粘贴以下代码即可:

dependencies {
  compile 'com.loopj.android:android-async-http:1.4.9'
}

服务器端主要是实现文件的读取功能:使用的组件是Commons-FileUpload.jar和commons-io.jar文件

下面是我的文件上传的实现

Web服务器端的代码(UploadSer.java):

package com.lzl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadSer
 */
@WebServlet("/UploadSer")
public class UploadSer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String PATH = "F://fileUpload";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadSer() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//将文件保存到-->F://filesUpload目录下
		File file = new File(PATH);
		if(!file.isDirectory()&&!file.exists()){
			//文件不存在
			System.out.println("文件不存在需要创建");
			file.mkdir();
		}
		PrintWriter pw = response.getWriter();
		try{
			//1、创建一个 DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//2、创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			//解决文件上传文件名的中文乱码
			upload.setHeaderEncoding("utf-8");
			//3、判断提交上来的数据是否是上传表单的数据
			if(!upload.isMultipartContent(request)){
				return ;
			}
			//4、使用ServletFileUpload解析器解析上传的数据,解析结果是一个List
			//集合,每一个FileItem对应一个Form表单的输入项
			List list = upload.parseRequest(request);
			for(FileItem item : list){
				//如果fileitem中封装的是普通的输入数据项
				if(item.isFormField()){
					String name = item.getFieldName();
					//解决普通输入项的数据的中文乱码问题
					String value= item.getString("utf-8");
					//
					System.out.println("name==="+value);
				}else{//如果是上传的文件
					String filename = item.getName();
					System.out.println("filename="+filename);
					if(filename==null||filename.trim().equals("")){
						continue;
					}
					filename = filename.substring(filename.lastIndexOf("\\")+1);
					//获取文件上传得到的输入流
					InputStream is = item.getInputStream();
					//获取一个文件的输出流
					FileOutputStream out = new FileOutputStream(PATH+"\\"+filename);
					//获取问
					byte[] b = new byte[1024*1024];
					int len = 0;
					while((len=is.read(b))!=-1){
						out.write(b, 0, len);
						out.flush();
					}
					is.close();
					out.close();
					//处理文件上传时生成的临时文件
					item.delete();
					pw.println("文件上传成功");
				}
			}
		}catch(Exception e){
			pw.println("文件上传失败");
		}
	}

}

package lzl.edu.com.clientdemo;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;

import cz.msebera.android.httpclient.Header;
import lzl.edu.com.clientdemo.Util.MySmartImageView;

public class MainActivity extends Activity {

    private Button mSelect,mUpload;
    private EditText mPath,mUploadPath;
    private MySmartImageView mImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSelect = (Button)findViewById(R.id.select);
        mPath = (EditText)findViewById(R.id.path);
        mUpload = (Button)findViewById(R.id.upload);
        mUploadPath = (EditText)findViewById(R.id.uploadPath);
        mImage=(MySmartImageView)findViewById(R.id.image);

        mUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //异步访问服务器端
                    AsyncHttpClient client = new AsyncHttpClient();
                    String path = "http://192.168.1.104:8080/FileUpload/UploadSer";
                    String uri = mUploadPath.getText().toString();
                    RequestParams params = new RequestParams();
                    //上传文件
                    params.put("file", new File(uri));
                    client.post(path, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int i, Header[] headers, byte[] bytes) {
                            Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                            Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_LONG).show();
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
                }
        });
        mSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String path = mPath.getText().toString().trim();
                Log.i("图片的资源路径:",path);
                Log.i("ruesult:",TextUtils.isEmpty(path)+"");
                if(!TextUtils.isEmpty(path)){
                    mImage.setImageURL(path,R.mipmap.ic_launcher);
                }
            }
        });
    }

}

布局很简单,这里不再给出。一下是效果图

网络编程---Android开源组件(Async-http)实现文件上传_第1张图片


你可能感兴趣的:(安卓基础)