安卓上传文件到服务器源码 - 云代码

8 篇文章 0 订阅
4 篇文章 0 订阅

完整源码:http://yuncode.net/code/c_5063ece6eba2d94

 

 

客户端
 
001package com.example.testandroid;
002  
003import java.io.DataOutputStream;
004import java.io.FileInputStream;
005import java.io.InputStream;
006import java.net.HttpURLConnection;
007import java.net.URL;
008  
009import android.app.Activity;
010import android.app.AlertDialog;
011import android.content.DialogInterface;
012import android.os.Bundle;
013import android.view.View;
014import android.widget.Button;
015import android.widget.TextView;
016  
017public class PhotoUpload extends Activity {
018    private String newName = "image.jpg";
019    private String uploadFile = "/sdcard/image.JPG";// 要上传的文件
020    private String actionUrl = "http://192.168.0.1:8080/PhotoUpload/servlet/UploadServlet";
021    private TextView mText1;
022    private TextView mText2;
023    private Button mButton;
024  
025    @Override
026    public void onCreate(Bundle savedInstanceState) {
027        super.onCreate(savedInstanceState);
028        setContentView(R.layout.activity_main);
029        mText1 = (TextView) findViewById(R.id.myText2);
030        // 文件路径:
031        mText1.setText(uploadFile);
032        mText2 = (TextView) findViewById(R.id.myText3);
033        // 上传网址:
034        mText2.setText(actionUrl);
035        /* 设置mButton的onClick事件处理 */
036        mButton = (Button) findViewById(R.id.myButton);
037        mButton.setOnClickListener(new View.OnClickListener() {
038            public void onClick(View v) {
039                uploadFile();
040            }
041        });
042    }
043  
044    /* 上传文件至Server的方法 */
045    private void uploadFile() {
046        String end = "\r\n";
047        String twoHyphens = "--";
048        String boundary = "*****";
049        try {
050            URL url = new URL(actionUrl);
051            HttpURLConnection con = (HttpURLConnection) url.openConnection();
052            /* 允许Input、Output,不使用Cache */
053            con.setDoInput(true);
054            con.setDoOutput(true);
055            con.setUseCaches(false);
056  
057            // 设置http连接属性
058            con.setRequestMethod("POST");
059            con.setRequestProperty("Connection", "Keep-Alive");
060            con.setRequestProperty("Charset", "UTF-8");
061            con.setRequestProperty("Content-Type",
062                    "multipart/form-data;boundary=" + boundary);
063  
064            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
065            ds.writeBytes(twoHyphens + boundary + end);
066            ds.writeBytes("Content-Disposition: form-data; "
067                    + "name=\"file1\";filename=\"" + newName + "\"" + end);
068            ds.writeBytes(end);
069  
070            // 取得文件的FileInputStream
071            FileInputStream fStream = new FileInputStream(uploadFile);
072            /* 设置每次写入1024bytes */
073            int bufferSize = 1024;
074            byte[] buffer = new byte[bufferSize];
075            int length = -1;
076            /* 从文件读取数据至缓冲区 */
077            while ((length = fStream.read(buffer)) != -1) {
078                /* 将资料写入DataOutputStream中 */
079                ds.write(buffer, 0, length);
080            }
081            ds.writeBytes(end);
082            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
083  
084            fStream.close();
085            ds.flush();
086            /* 取得Response内容 */
087            InputStream is = con.getInputStream();
088            int ch;
089            StringBuffer b = new StringBuffer();
090            while ((ch = is.read()) != -1) {
091                b.append((char) ch);
092            }
093            /* 将Response显示于Dialog */
094            showDialog("上传成功" + b.toString().trim());
095            /* 关闭DataOutputStream */
096            ds.close();
097        } catch (Exception e) {
098            showDialog("上传失败" + e);
099        }
100    }
101  
102    /* 显示Dialog的method */
103    private void showDialog(String mess) {
104        new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")
105                .setMessage(mess)
106                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
107                    public void onClick(DialogInterface dialog, int which) {
108                    }
109                }).show();
110    }
111}


服务器端
 
01package com.demo;
02  
03import java.io.File;
04import java.io.IOException;
05import java.util.Date;
06import java.util.Iterator;
07import java.util.List;
08  
09import javax.servlet.ServletException;
10import javax.servlet.http.HttpServlet;
11import javax.servlet.http.HttpServletRequest;
12import javax.servlet.http.HttpServletResponse;
13  
14import org.apache.commons.fileupload.DiskFileUpload;
15import org.apache.commons.fileupload.FileItem;
16  
17public class UploadServlet extends HttpServlet {
18    public void doPost(HttpServletRequest request, HttpServletResponse response)
19            throws ServletException, IOException {
20  
21        String temp = request.getSession().getServletContext().getRealPath("/")
22                + "temp"; // 临时目录
23        System.out.println("temp=" + temp);
24        String loadpath = request.getSession().getServletContext()
25                .getRealPath("/")
26                + "Image"; // 上传文件存放目录
27        System.out.println("loadpath=" + loadpath);
28        DiskFileUpload fu = new DiskFileUpload(); // 需要导入commons-fileupload-1.2.2.jar
29                                                    // http://commons.apache.org/fileupload/
30        fu.setSizeMax(1 * 1024 * 1024); // 设置允许用户上传文件大小,单位:字节
31        fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节
32        fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
33  
34        // 开始读取上传信息
35        int index = 0;
36        List fileItems = null;
37  
38        try {
39            fileItems = fu.parseRequest(request);
40            System.out.println("fileItems=" + fileItems);
41        } catch (Exception e) {
42            e.printStackTrace();
43        }
44  
45        Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
46        while (iter.hasNext()) {
47            FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
48            if (!item.isFormField()) {
49                String name = item.getName();// 获取上传文件名,包括路径
50                name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
51                long size = item.getSize();
52                if ((name == null || name.equals("")) && size == 0)
53                    continue;
54                int point = name.indexOf(".");
55                name = (new Date()).getTime()
56                        + name.substring(point, name.length()) + index;
57                index++;
58                File fNew = new File(loadpath, name);
59                try {
60                    item.write(fNew);
61                } catch (Exception e) {
62                    // TODO Auto-generated catch block
63                    e.printStackTrace();
64                }
65  
66            } else// 取出不是文件域的所有表单信息
67            {
68                String fieldvalue = item.getString();
69                // 如果包含中文应写为:(转为UTF-8编码)
70                // String fieldvalue = new
71                // String(item.getString().getBytes(),"UTF-8");
72            }
73        }
74        String text1 = "11";
75        response.sendRedirect("result.jsp?text1=" + text1);
76    }
77}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT开发者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值