Android上传文件到linux服务器

Android上传文件到服务器

欢迎访问本人博客:www.xuanworld.top

本文使用的是通过tomcat下servlet的方式进行的服务器配置

服务器方面

public static void uploadManage(File uploadFile){
        String boundary = "*****";
        try {
            URL url = new URL("http://xxxxxxx/upload/upload");//你的服务器地址
            HttpURLConnection con = (HttpURLConnection)url.openConnection();

            // 允许Input、Output,不使用Cache
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);

            con.setConnectTimeout(50000);
            con.setReadTimeout(50000);
            // 设置传送的method=POST
            con.setRequestMethod("POST");
            //在一次TCP连接中可以持续发送多份数据而不会断开连接
            con.setRequestProperty("Connection", "Keep-Alive");
            //设置编码
            con.setRequestProperty("Charset", "UTF-8");
            //text/plain能上传纯文本文件的编码格式
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            con.setRequestProperty("filename",uploadFile.getName());
            // 设置DataOutputStream
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());

            // 取得文件的FileInputStream
            FileInputStream fStream = new FileInputStream(uploadFile);
            // 设置每次写入1024bytes
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int length = -1;
            // 从文件读取数据至缓冲区
            while ((length = fStream.read(buffer)) != -1) {
                // 将资料写入DataOutputStream中
                ds.write(buffer, 0, length);
            }
            ds.flush();
            fStream.close();
            ds.close();
            if(con.getResponseCode() == 200){
                System.out.println("文件上传成功!上传文件为:" + uploadFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Http","报错信息toString:" + e.toString());
            System.out.println("文件上传失败!上传文件为:" + uploadFile);
            System.out.println("报错信息toString:" + e.toString());
        }
    }

Android端

import java.io.*;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadServlet extends HttpServlet {
    String path="/home/AndroidTest";
    String filename;
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().println("<h1>Hello Servlet!</h1>");
            response.getWriter().println(new Date().toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException {
        InputStream is = request.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        filename=request.getHeader("filename");
        System.out.println(filename+"+++++++++++");
        String result = "";
        try {
            result = saveFile(dis);
        } catch (Exception e) {
            System.out.println(e);
            result = "upload error!!!";
        }
        System.out.println(result);

        request.getSession().invalidate();
        response.setContentType("image/jpeg;charset=UTF-8");
        ObjectOutputStream dos = new ObjectOutputStream(
                response.getOutputStream());
        dos.writeObject(result);
        dos.flush();
        dos.close();
        dis.close();
        is.close();
    }
    private String saveFile(DataInputStream dis) {
        File file = new File(path+"/"+filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println(e);
            }
        }
        FileOutputStream fps = null;
        try {
            fps = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int length = -1;

        try {
            while ((length = dis.read(buffer)) != -1) {
                fps.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fps.flush();
            fps.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return "success";
    }
}

一些补充

如果想获得文件名的话可以在请求头head中加入filename元素。

Android要进行网络传输需要进行相关的权限申请,申请方法请见官方文档。

服务端搭好后可以直接在网络上访问上传地址,如果看到hello servlet就说明服务端搭建完成。

不要忘记在web.xml和index.jsp中进行更新数据,方法不再赘述。

后记

Android开发是很久以前学的,因此不打算从头开始更新笔记了,准备更新之前完成的一些比较有用的Android技术的实现方法。

Android会不定期更新。

欢迎进行各类Android,web技术,或AI神经网络的交流,web前后端都可以交流。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值