利用xutils框架在Android上传多个文件到Struts搭建的java服务器

现在Android+SSH服务器非常流行,因为最近业务需要实现利用Android发表博客的需求,这个时候就需要上传多个文件到服务器中。因为现在框架都非常好用,不需要自己从底层自己开始搭建框架。网络上面的大多数都是Android+Servlet实现的Android上传功能。这里因为我用的是SSH框架进行开发的,所以当然要用Struts2来代替Servlet的功能来实现文件接收的功能,Android中利用xutils框架实现上传的功能。

这里有一个我测试成功的demo,所以我拿来分享一下。


Android端的核心代码:

Android端用的是xutils框架进行文件传输的,这里就不多介绍xutils框架了,有兴趣的可以自己去Google或者百度。

<span style="font-size:14px;">package com.example.zt.xutilsupload;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @ViewInject(R.id.btn)
    private Button btn;
    private String filepath;
    private String filepath1;
    @ViewInject(R.id.imageView)
    ImageView imageView;
    private RequestParams requestParams;
    private String string="http://10.2.41.50:8080/HY/appDownLoadAction.action";//这里是服务器中action的地址

    private List<File> list=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x.view().inject(this);
        init();
        btn.setOnClickListener(this);
    }

    private void init() {
        filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator;
        filepath1= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"abc.txt";
        FileInputStream fis = null;//文件输入流
        try {
            fis = new FileInputStream(new File(filepath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Bitmap bmp = BitmapFactory.decodeStream(fis);
        imageView.setImageBitmap(bmp);
        requestParams=new RequestParams(string);

       for(int i=1;i<=3;i++)
       {
           Log.i("F",filepath+"a0"+i+"jpg");
           list.add(new File(filepath+"a0"+i+".jpg"));
       }
        list.add(new File(filepath1));

        requestParams.addBodyParameter("username","上传图片");
        for(int i=0;i<list.size();i++)
        {
            requestParams.addBodyParameter("file",list.get(i));
        }




    }

    @Override
    public void onClick(View v) {
        x.http().post(requestParams, new Callback.CacheCallback<String>() {

            @Override
            public void onSuccess(String result) {
                btn.setText(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });

    }
}
</span>

SSH服务器的核心代码:

这里用的是Struts2来进行文件接收的。

<span style="font-size:14px;">package com.ge.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
public class AppDownLoadAction {
	private String username;
	// 这里用List来存放上传过来的文件,file同样指的是临时文件夹中的临时文件,而不是真正上传过来的文件
	private List<File> file;
	// 这个List存放的是文件的名字,和List<File>中的文件相对应
	private List<String> fileFileName;
	private List<String> fileContentType;
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public List<File> getFile() {
		return file;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	public void execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter printWrite=response.getWriter();
		String root = ServletActionContext.getServletContext().getRealPath(
				"/upload");//获取项目所在文件的具体地址信息
		for (int i = 0; i < file.size(); i++) {
		byte[] buffer = new byte[20];
		BufferedInputStream reader=new BufferedInputStream(new FileInputStream(file.get(i)));
		BufferedOutputStream writer=new BufferedOutputStream(new FileOutputStream(new File(root,fileFileName.get(i))));
		int length = 0;
		while (-1 != (length = reader.read(buffer, 0, buffer.length))) {
			writer.write(buffer,0,length);//这里非常重要,千万不要写成writer.write(buffer)
		}
		writer.flush();
		printWrite.write("success........成功了");
		reader.close();
		writer.close();
		printWrite.close();
		}
	}
}
</span>

Struts2中的配置信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.multipart.saveDir" value="C:/repository"/>  
	<constant name="struts.devMode" value="true" />
	<package name="HY" namespace="/" extends="struts-default">
	    <action name="appDownLoadAction" class="AppDownLoadAction">
	</package>
</struts>

这里的AppDownLoadAction是在Spring中配置的,比较简单我就不多介绍了。

到这里多个文件上传的功能就完成了


如果大家按这个步骤还是出问题,可以下载我成功的一个demo,这是下载地址:点击打开链接


要是还有问题的话可以加我微信或QQ联系我:QQ:208017534  微信:qiang220316            欢迎一起交流一起进步。

                                                                       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值