前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用xutils框架在Android上传多个文件到Struts搭建的java服务器

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

作者头像
林老师带你学编程
发布2022-11-30 10:26:16
5790
发布2022-11-30 10:26:16
举报
文章被收录于专栏:强仔仔

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

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

Android端的核心代码:

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

代码语言:javascript
复制
<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来进行文件接收的。

代码语言:javascript
复制
<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中的配置信息:

代码语言:javascript
复制
<?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,这是下载地址:点击打开链接

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档