android 向 .net服务器上传文件

本文介绍了一种从Android客户端上传文件至ASPX接口的方法。通过使用HTTP POST请求及multipart/form-data格式,实现了文件传输的功能。代码示例中包含了客户端上传流程与服务器端接收逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android 客服端:

/**
     * 上传文件到aspx接口   
     * @param SendUrl  上传文件接口接收的地址  .aspx?params  
     * @param filePath 文件自身的地址
     */
    public void uploadFile(final String SendUrl, final String filePath) {
        Log.i("tag", "uploadFile/IssueActivity");
        final String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 换行符
                    final String newLine = "\r\n";
                    final String boundaryPrefix = "--";
                    // 定义数据分隔线
                    String BOUNDARY = "======123========";
                    // 服务器的域名
                    URL url = new URL(SendUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    // 设置为POST情
                    conn.setRequestMethod("POST");
                    // 发送POST请求必须设置如下两行
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    // 设置请求头参数
                    conn.setRequestProperty("connection", "Keep-Alive");
                    conn.setRequestProperty("Charsert", "UTF-8");
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                    conn.addRequestProperty("username", "syw4188471002");
                    conn.addRequestProperty("password", "12252252a");
                    OutputStream out = new DataOutputStream(conn.getOutputStream());
                    //
                    handler.sendEmptyMessage(ShowDialog);
                    // 文件头信息
                    StringBuilder sb = new StringBuilder();
                    sb.append(boundaryPrefix);
                    sb.append(BOUNDARY);
                    sb.append(newLine);
//                     文件参数,photo参数名可以随意修改
                    sb.append("Content-Disposition: form-data;name=\"photo\";filename=\"" + fileName
                            + "\"" + newLine);
                    sb.append("Content-Type:application/octet-stream");
//                     参数头设置完以后需要两个换行,然后才是参数内容
                    sb.append(newLine);
                    sb.append(newLine);
                    // 将参数头的数据写入到输出流中
                    out.write(sb.toString().getBytes());

                    // 数据输入流,用于读取文件数据
                    File file = new File(filePath);
                    DataInputStream in = new DataInputStream(new FileInputStream(
                            file));
                    byte[] bufferOut = new byte[4096];
                    int bytes = 0;
                    // 每次读1KB数据,并且将文件数据写入到输出流中
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    out.flush();
                    // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
                    byte[] end_data = (newLine+newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
                    // 写上结尾标识
                    out.write(end_data);
                    out.flush();
                    in.close();
                    out.close();

                    handler.sendEmptyMessage(Success);

                    // 定义BufferedReader输入流来读取URL的响应
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        Log.i("tag", line);
                    }
                    conn.disconnect();
                } catch (Exception e) {
                    if (dialog != null)
                        handler.sendEmptyMessage(CloseDialog);
                    Log.i("tag", e.toString());
                }

            }
        }).start();
    }
.net 服务端
<script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            byte[] buffer = new byte[Request.InputStream.Length];
            Request.InputStream.Read(buffer, 0, buffer.Length);
            if (buffer.Length>0)
            {
                try
                {
                    string physicsPath = Server.MapPath(Request.ApplicationPath);
                    string fileName = Request["fileName"];
                    string filePath = physicsPath+"images\\"+ fileName;
                    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(buffer);
                    bw.Flush();
                    bw.Close();
                }
                catch(Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else
            {
                Response.Write("文件长度为0");
            }
        }
    </script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值