手机PC文件传输

QQ啥的现在直接无法全部退出,很纠结后台运行,时不时的来条消息,明明电脑QQ还开着,越来越流氓了。

服务端代码:

<%@ Page Language="C#" %>

<script runat="server">

   static readonly string C_FileRoot = "/PFiles/";

    private System.Web.Script.Serialization.JavaScriptSerializer Serializer { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
           Serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            Response.ContentType = "text/json";
            Response.Expires = -1;

            var method = Request["m"];

            if (string.Compare(method, "upload", true) == 0)
            {
                DoUpload();
            }
            else if (string.Compare(method, "checkUpdate", true) == 0)
            {
                DoCheckUpdate();
            }
            else if (string.Compare(method, "download", true) == 0)
            {
                DoDownload();
            }
            else if (string.Compare(method, "getList", true) == 0)
            {
                DoGetList();
            }
            else
            {
                DoShow();
            }

    }
    private void DoShow()
    {
        Response.ContentType = "text/html";
    }
    private void DoGetList()
    {
        var sb = new StringBuilder();
        var clientNo = Request["ClientNo"];
        using (var writer = new HtmlTextWriter(new System.IO.StringWriter(sb)))
        {

            Repeater1.DataSource = Queue.Where(ent => ent.ClientNo == clientNo).OrderByDescending(ent => ent.AddTime).Take(100).ToList();
            Repeater1.DataBind();
            Repeater1.RenderControl(writer);
            writer.Flush();
        }

        Response.Write(sb.ToString());
        Response.End();
    }
    private void DoCheckUpdate()
    {
        try
        {
            var clientNo = Request["ClientNo"];
            var maxAddTime = Queue.Where(ent => ent.ClientNo ==clientNo).Max(ent=>ent.AddTime);
            if (maxAddTime == null) maxAddTime = new DateTime(2015, 07, 12);
            Response.Write(Serializer.Serialize(new BaseResponse<String>(){Code=0,Msg=DateTime.Now.ToString(),Model=maxAddTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}));

        }
        catch (Exception ex)
        {
            var resp = new FilePostResponse() { Code = -1, Msg = Uri.EscapeUriString(ex.Message) };
            Response.Write(Serializer.Serialize(resp));
        }
        Response.End();
    }
    private void DoDownload()
    {
        try
        {
            long  id =long.TryParse( Request["FId"],out id) ? id : -1;
            var doc = Queue.FirstOrDefault(ent => ent.FileId == id);
            if (doc != null)
            {
                Response.ContentType = doc.MIME;
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(doc.Name + System.IO.Path.GetExtension(doc.Path), Encoding.GetEncoding("utf-8")));

                Response.TransmitFile(System.Web.Hosting.HostingEnvironment.MapPath(doc.Path));
                Response.Flush();
            }
            else
            {
                throw new Exception("文件不存在!");
            }
        }
        catch (Exception ex)
        {
            var resp = new FilePostResponse() { Code = -1, Msg = Uri.EscapeUriString(ex.Message) };
            Response.Write(Serializer.Serialize(resp));
        }
        Response.End();
    }
    private void DoUpload()
    {
        try
        {

            if (Request.Files.Count <= 0) throw new Exception("没有文件上传!");

            SaveFile();
        }
        catch (Exception ex)
        {
            var resp = new FilePostResponse() { Code = -1, Msg = Uri.EscapeUriString(ex.Message) };
            Response.Write(Serializer.Serialize(resp));
        }
        Response.End();
    }

        private void  SaveFile()
        {

            var file = Request.Files[0];
            var ext = System.IO.Path.GetExtension(file.FileName);

            //确保目录存在
            string path =  C_FileRoot + DateTime.Now.ToString("yyyy-MM-dd") + "/";

            if (!System.IO.Directory.Exists( System.Web.Hosting.HostingEnvironment.MapPath(path)))
            {
                System.IO.Directory.CreateDirectory(System.Web.Hosting.HostingEnvironment.MapPath(path));
            }
            //合成文件名
            var filename= path + Guid.NewGuid().ToString("N").Substring(0,8) + ext;

            var resp = new FilePostResponse();
            resp.MIME = file.ContentType;
            resp.Size = file.ContentLength / 1024;
            resp.ClientNo = Request["ClientNo"];
            resp.Name =Uri.EscapeUriString( System.IO.Path.GetFileNameWithoutExtension(file.FileName));
            resp.Path =Uri.EscapeUriString( filename);
            resp.Code = 0;
            resp.Msg = "Success";

            //保持文件
            file.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath(filename));

            Response.Write(Serializer.Serialize(resp));
            EnQueue(resp);
        }

        private static int GFileId = 0;
        private static System.Collections.Concurrent.ConcurrentQueue<FilePostResponse> Queue = new System.Collections.Concurrent.ConcurrentQueue<FilePostResponse>();
        private void EnQueue(FilePostResponse fp)
        {
            if (Queue.Count > 1200)
            {
                while (Queue.Count > 800)
                {
                    FilePostResponse outIt = null;
                    Queue.TryDequeue(out outIt);
                }
            }
            Queue.Enqueue(fp);
        }
        public class BaseResponse<T>
        {
            public int Code { get; set; }
            public String Msg { get; set; }
            public T Model { get; set; }
        }
        public class FilePostResponse
        {
            public FilePostResponse()
            {
                System.Threading.Interlocked.Increment(ref GFileId);
                this.FileId = GFileId;
                AddTime = DateTime.Now;
            }
            public int Code { get; set; }
            public string Msg { get; set; }
            public string Path { get; set; }
            public string Name { get; set; }
            public long Size { get; set; }
            public string MIME { get; set; }
            public long FileId { get; set; }
            public DateTime? AddTime { get; set; }
            public String ClientNo{get;set;}

        }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>手机PC文件传输</title>
<link href="/Styles/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        var lastUploadTime = "2015-07-10";
        $(document).ready(function () {
            setInterval(queryData, 1000);
        });

        function queryData() {

            var clientNo = $("#clientNo").val();
            if (clientNo == null || clientNo == "") return;

            var url = "/FilePost.aspx?m=checkUpdate&clientNo=" + clientNo;

            $.getJSON(url, function (json) {
                if (json.Code == 0) {
                    $("#freshTime").text(json.Msg);
                    if (json.Model > lastUploadTime) {
                        lastUploadTime = json.Model;
                        //console.log(json.Model);
                        var getListUrl = "/FilePost.aspx?m=getList&clientNo=" + clientNo;
                        $("#panelShow").load(getListUrl, { m: "getList()", rnd: new Date().getTime() });
                    }
                } else {
                   // console.log(json.Msg);
                    $("#tips").text(unescape(json.Msg));
                }

            });
        }

    </script>

</head>
<body>

    <div class="page">
        <div class="header">
            <div class="title">
                <h1>
                   手机PC文件传输
                </h1>
            </div>
            <div class="loginDisplay">

                        [ <a href="#" id="HeadLoginView_HeadLoginStatus">登录</a> ]

            </div>
            <div class="clear hideSkiplink">

            </div>
        </div>
        <div class="main">

        <h2>
            FILE POST
        </h2>
        <div> <input type="text" id="clientNo" value="" />注意:必须提供手机上的编号,<span id="freshTime"></span> </div>
       <div id="panelShow" >
      <asp:Repeater ID="Repeater1" runat="server">
                  <HeaderTemplate>
                <table style="width: 100%; background-color: #eeeeee" cellspacing="2">
                    <tr style="background-color: White; font-weight: bold">

                        <td style="width: 6%">
                            编号
                        </td>
                        <td style="width: 20%">
                            文件名
                        </td>
                        <td style="width: 25%; text-align: center">
                            类型
                        </td>
                        <td style="width: 20%; text-align: center">
                          时间
                        </td>
                        <td style="text-align: center">
                           &nbsp;
                        </td>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr style="background-color: White;">

                    <td>
                       <%#Eval("FileId") %>
                    </td>
                    <td>
                     <%#Eval("Name") %>
                    </td>
                    <td style="text-align: center">
                         <%#Eval("MIME")%>
                    </td>
                     <td style="text-align: center">
                         <%#Eval("AddTime")%>
                    </td>

                     <td style="text-align: center">
                         <a href=‘FilePost.aspx?m=download&FId=<%#Eval("FileId") %>‘ target="_blank">下载</a>
                    </td>

                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
      </div>
       <div id="tips"></div>

        </div>
        <div class="clear">
        </div>
    </div>
    <div class="footer">

    </div>

</body>
</html>

Android

package cn.fstudio.filepost;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.UUID;

import sync.http.AsyncHttpClient;
import sync.http.AsyncHttpResponseHandler;
import sync.http.RequestParams;
import cn.fstudio.util.PreferencesUtils;
import cn.fstudio.util.StringUtil;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import android.provider.MediaStore;

public class MainActivity extends Activity implements OnClickListener {

    Button btnSave = null;
    EditText txtUrl = null;
    TextView txtNo=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        handleSendIntent();

    }

    private void handleSendIntent() {
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {

            Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
            if (uri != null) {

                UploadFile( uri);
            }

        }
    }

    private void initView() {
        txtNo=(TextView)findViewById(R.id.txtNo);
        btnSave = (Button) findViewById(R.id.button1);
        btnSave.setOnClickListener(this);
        txtUrl = (EditText) findViewById(R.id.textView1);
        String url = PreferencesUtils.getStringPreference(
                getApplicationContext(), "url", "192.168.9.5:7986");
        txtUrl.setText(url);

        String clientNo = PreferencesUtils.getStringPreference(
                getApplicationContext(), "ClientNo", "");
        txtNo.setText(clientNo);
        Log.i("T","ClientNO:" + clientNo);

        if(StringUtil.isNullOrEmpty(clientNo)){
          clientNo=     UUID.randomUUID().toString().replace("-", "").substring(14,20);
          Toast.makeText(this, clientNo, Toast.LENGTH_LONG).show();
          txtNo.setText(clientNo);
            PreferencesUtils.setStringPreferences(this,
                    "ClientNo", clientNo);
        }
    }

    /* Begin Upload file */
    private ProgressDialog dialog;

    private void UploadFile(Uri uri) {
        String ip = txtUrl.getEditableText().toString();
        String clientNo=txtNo.getText().toString();
        String file_path ="";

        String url = "http://" + ip + "/filePost.aspx?m=upload&ClientNo=" + clientNo;
        Log.d("T", url);

        /*处理 媒体 Uri类型*/
        if (uri.toString().startsWith("content:")) {

            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor actualimagecursor = this.managedQuery(uri, proj, null, null,null);
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();

            file_path = actualimagecursor.getString(actual_image_column_index);
            actualimagecursor.close();
        }else {
            file_path=uri.getPath();
        }
        /*上传文件参数*/
        RequestParams requestParams = new RequestParams();
        Log.i("T","file_path" +file_path);
        File file = new File(file_path);
        try {
            requestParams.put("file", file);
        } catch (FileNotFoundException e) {
            Log.d("T", e.getMessage());
        }
        AsyncHttpClient client = new AsyncHttpClient();
        client.post(url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT)
                .show();
                Log.d("T", response);

            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub

                dialog = ProgressDialog.show(MainActivity.this, null,
                        "正在上传文件...");
            }

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub

                dialog.dismiss();
                super.onFinish();
                //MainActivity.this.finish();
            }

            @Override
            public void onFailure(Throwable error, String content) {
                Log.d("T", content);
                Toast.makeText(MainActivity.this, "上传失败!", Toast.LENGTH_SHORT)
                        .show();
                super.onFailure(error, content);
            }
        });
    }

    /* End Upload File */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        if (arg0.getId() == R.id.button1) {

            String urlString = txtUrl.getText().toString();
            PreferencesUtils.setStringPreferences(getApplicationContext(),
                    "url", urlString);

            Toast.makeText(this, "配置已经保存", Toast.LENGTH_SHORT).show();
        }
    }

}

Android 配置文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.fstudio.filepost"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.RUN_INSTRUMENTATION" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.SEND_SMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_SMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_OWNER_DATA" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cn.fstudio.filepost.MainActivity"
            android:screenOrientation="portrait"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="*/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>
    </application>

</manifest>

时间: 2024-11-04 01:55:01

手机PC文件传输的相关文章

arm-linux笔记3:arm-linux PC文件传输方法总结(4种最常见的方法)

arm-linux笔记3:arm-linux PC文件传输方法总结(4种最常见的方法) 1使用串口终端传输文件 2使用ftp传输文件 3使用nfs传输文件 4使用u盘拷贝 串口的优点是方法简单,不需要过多的配置,不需要联接网络,但是发送数据的速度比较慢,不适用于传输超过10M的文件 ftp的配置的时候需要联网,还需要下载ftp服务以及进行复杂的配置,大小文件传输速度都比较快,但是好像只能传输单个文件,没有nfs方便 nfs配置的时候也需要联网,还需要下载nfs服务以及进行复杂的配置,配置好了之后

Android 用Socket实现PC和手机的文件传输

PC服务器端代码: /* * PC与<a href="http://lib.csdn.net/base/android" class='replace_word' title="Android知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Android</a>客户端实现文件的传送 * PC服务器端 */ package com.<a href="ht

微信文件传输助手文件夹在哪?一起来找找

微信文件传输助手是微信电脑版与手机微信之间相互传输图片等文件的好工具,但很多童鞋都找不到微信文件传输助手文件夹在哪,就让我们一起找找吧 1.先说说手机微信文件传输助手文件夹在哪吧 文件夹路径为/Tencent/MicroMsg/Download/ 2.电脑版微信文件传输助手文件夹在:/微信安装保存目录/wechat files/微信号/ 也可以点击接收到的图片下载保存到相应位置即可

非阻塞socket实现android手机与PC的文件传输

项目需要是通过WIFI建立手机和PC的通信,然后自定义一个简单的协议对要传输的文件进行校验,传输的文件是2张3M的图片,要求考虑网络中断情况处理. 我这里采用的是非阻塞socket来实现的,之前查过很多资料,觉得这种比较方便,其实用传统的那种socket也是可以实现的,至于阻塞问题,可以开两个线程,这样保证读取不是同一个线程,也就可以解决. 程序大致是这样的流程,手机端发送一个"filename"字符串给PC,PC校验字符串后返回文件名,然后手机端再把接收到的文件名发送给PC端,进行校

如何把云端服务器上的file04.c文件传输到本地pc机windows系统上去呢?

一般服务器会放在机房,很多时候我们一般是通过一某个终端软件进行远程连接到服务器,然后再去工作. 那么我们如何把云端服务器上的file04.c文件传输到本地pc机windows系统上去呢? 1.在SecureCRT上的链接对话框右键打开 之后选择 连接SFTP会话2.在sftp里面要分别要进入远程服务器的路径和本地的路径,如下: 先用命令pwd 查看远程的linux的目录 cd /home/chen/001/01/文件操作day01/   进入远程的linux下存放文件的目录 lpwd 查看本地的

嵌入式系统下文件传输实验

TCP网络通信编程,多线程(代码见附录) 实验目的: 实现PC与物联网试验箱间传输文件,PC作为客户端,在PC上输入一个文件名,通过编制的程序上传到物    联网试验箱上.传输协议采用TCP协议.在PC的linux系统上运行client,在物联网试验箱的linux系统上运    行server.实验步骤:   (1)在PC端打开虚拟机(unbuntu系统),将实验板接上电源并使用网线将开发板与PC相连.   (2)使用命令ifconfig eth0 192.168.1.21设置PC端IP地址, 

Socket编程一实现简易的聊天功能以及文件传输

干程序是一件枯燥重复的事,每当感到内心浮躁的时候,我就会找小说来看.我从小就喜爱看武侠小说,一直有着武侠梦.从金庸,古龙,梁羽生系列到凤歌(昆仑),孙晓(英雄志)以及萧鼎的(诛仙)让我领略着不一样的江湖. 如果你有好看的武侠系列小说,给我留言哦.题外话就扯这么多了,接着还是上技术. 看看今天实现的功能效果图: 可以这里使用多台手机进行通讯,[凤歌]我采用的服务器发送消息. 是不是只有发送消息,有些显得太单调了.好,在发送消息的基础上增加文件传输.后期会增加视频,音频的传输,增加表情包.那一起来看

android -- 蓝牙 bluetooth (四)OPP文件传输

在前面android -- 蓝牙 bluetooth (一) 入门文章结尾中提到了会按四个方面来写这系列的文章,前面已写了蓝牙打开和蓝牙搜索,这次一起来看下蓝牙文件分享的流程,也就是蓝牙应用opp目录下的代码,作为蓝牙最基本的一个功能,这部分的代码在之前的版本中就已经有了,新旧版本代码对比很多类名都是一样的,这一部分新东西不多,写在这里帮助大家梳理下流程吧. 有没有这种感觉,智能手机的普及让我们提高了一点对蓝牙的关注,手机间使用蓝牙互传文件应该是最常用的应用之一,手机与电脑也可以通过蓝牙做同样的

基于FTP协议的文件传输工具(SOCKET、FTP方面、MFC方面)

一.本课程是怎么样的一门课程(全面介绍) 1.简介:FTP(File Transfer Protocol),是文件传输协议的简称.用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).用户可以通过它把自己的PC机与世界各地所有运行FTP协议的服务器相连,访问服务器上的大量程序和信息.2.作用:FTP的主要作用,就是让用户连接上一个远程计算机(这些计算机上运行着FTP服务器程序)查看远程计算机有哪些文件,然后把文件从远程计算机上拷到本地计算机,或把本地计算