手机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 = -;
var method = Request["m"];
if (string.Compare(method, "upload", true) == )
{
DoUpload();
}
else if (string.Compare(method, "checkUpdate", true) == )
{
DoCheckUpdate();
}
else if (string.Compare(method, "download", true) == )
{
DoDownload();
}
else if (string.Compare(method, "getList", true) == )
{
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().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(, , );
Response.Write(Serializer.Serialize(new BaseResponse<String>(){Code=,Msg=DateTime.Now.ToString(),Model=maxAddTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}));
}
catch (Exception ex)
{
var resp = new FilePostResponse() { Code = -, 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 : -;
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 = -, Msg = Uri.EscapeUriString(ex.Message) };
Response.Write(Serializer.Serialize(resp));
}
Response.End();
}
private void DoUpload()
{
try
{
if (Request.Files.Count <= ) throw new Exception("没有文件上传!");
SaveFile();
}
catch (Exception ex)
{
var resp = new FilePostResponse() { Code = -, Msg = Uri.EscapeUriString(ex.Message) };
Response.Write(Serializer.Serialize(resp));
}
Response.End();
}
private void SaveFile()
{
var file = Request.Files[];
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(,) + ext;
var resp = new FilePostResponse();
resp.MIME = file.ContentType;
resp.Size = file.ContentLength / ;
resp.ClientNo = Request["ClientNo"];
resp.Name =Uri.EscapeUriString( System.IO.Path.GetFileNameWithoutExtension(file.FileName));
resp.Path =Uri.EscapeUriString( filename);
resp.Code = ;
resp.Msg = "Success";
//保持文件
file.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath(filename));
Response.Write(Serializer.Serialize(resp));
EnQueue(resp);
}
private static int GFileId = ;
private static System.Collections.Concurrent.ConcurrentQueue<FilePostResponse> Queue = new System.Collections.Concurrent.ConcurrentQueue<FilePostResponse>();
private void EnQueue(FilePostResponse fp)
{
if (Queue.Count > )
{
while (Queue.Count > )
{
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, );
});
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 == ) {
$("#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="">
<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">
</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(,);
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>
手机PC文件传输的更多相关文章
- Android 用Socket实现PC和手机的文件传输
PC服务器端代码: /* * PC与<a href="http://lib.csdn.net/base/android" class='replace_word' title ...
- 非堵塞socket实现android手机与PC的文件传输
项目须要是通过WIFI建立手机和PC的通信,然后自己定义一个简单的协议对要传输的文件进行校验,传输的文件是2张3M的图片,要求考虑网络中断情况处理. 我这里採用的是非堵塞socket来实现的,之前查过 ...
- Linux主机上实现树莓派的交叉编译及文件传输,远程登陆
0.环境 Linux主机OS:Ubuntu14.04 64位,运行在wmware workstation 10虚拟机 树莓派版本:raspberry pi 2 B型. 树莓派OS:官网下的的raspb ...
- FTP远程文件传输命令
使用ftp命令进行远程文件传输 ftp命令是标准的文件传输协议的用户接口.ftp是在TCP/IP网络上的计算机之间传输文件的简单有效的方法.它允许用户传输ASCII文件和二进制文件. 在ftp会话过程 ...
- 【转】Cordova文件传输插件fileTransfer
任务要求: 访问手机的目录,选择一个文件,并使用该插件将指定文件传输到远程主机的某个指定目录中. HTML <!DOCTYPE html> <!-- Licensed to the ...
- android -- 蓝牙 bluetooth (四)OPP文件传输
在前面android -- 蓝牙 bluetooth (一) 入门文章结尾中提到了会按四个方面来写这系列的文章,前面已写了蓝牙打开和蓝牙搜索,这次一起来看下蓝牙文件分享的流程,也就是蓝牙应用opp目录 ...
- 与众不同 windows phone (13) - Background Task(后台任务)之后台文件传输(上传和下载)
原文:与众不同 windows phone (13) - Background Task(后台任务)之后台文件传输(上传和下载) [索引页][源码下载] 与众不同 windows phone (13) ...
- 搭建 Guacamole 并解决各种坑和创建不了虚拟驱动器导致无法实现文件传输的方法
系统类型版本:centos7 64位 结果:最终跑通了项目并且实现了虚拟驱动器的文件传输功能,添加了中文支持 反思总结: 先查看官方文档的Q&A,找找有没有类似的错误,然后如果有错误日志或者现 ...
- SSIS 学习之旅 FTP文件传输-脚本任务
这一章主要讲解一下用脚本怎么把CSV文件抛送到FTP服务器上 设计: 通过Demon库的Users表数据生成CSV文件. 生成后的CSV文件抛送到FTP指定目录下. 控件的使用这里就不做详细讲 ...
随机推荐
- phone手机比较
phone 15年5月3大厂商发布的高端机器 高颜值手机 皓月银 http://www.vmall.com/product/1983.html 冰川白 http://www.vmall.com/pro ...
- Oracle12c部署
部署环境业务系统与数据库服务部署在一台服务器上了 电脑是台式机没有网络,也没有插网线,需要先建立一个网络回环,然后进行Oracle12c的安装,安装过程中系统会默认勾选创建为容器数据库,需要把这个勾选 ...
- KKT条件的物理意义(转)
最好的解释:https://www.quora.com/What-is-an-intuitive-explanation-of-the-KKT-conditions# 作者:卢健龙链接:https:/ ...
- HTML的属性和css基础
1.name属性: name属性,用于指定标签元素的名称,<a>标签内必须提供href或name属性:<a name ="value"> 2.id属性: 1 ...
- HTML的实际演练2
1.html 换行: 如果你想在不产生新的段落下换行,就使用<br/><p>tishi is a praskdjf<br/>ldkfldj</p> 2. ...
- CentOS 6.3安装配置supervisor进程管理工具
1. Supervisor是一个C/S系统,它可以在类unix操作系统让用户来监视和控制后台服务进程的数量,一个很重要的功能就是监控服务器的主要后台进程,并在出现问题是自动重启. 2. 根据服务器上的 ...
- 第五章 二叉树(e5)重构
- cf451C-Predict Outcome of the Game
http://codeforces.com/problemset/problem/451/C A - Predict Outcome of the Game Time Limit:2000MS ...
- Java的线程同步
synchronized获取的锁是对象,而不是函数或语句块. 项目结构 资源类 import java.util.concurrent.TimeUnit; public class myResourc ...
- C#.net随机数函数
(1)Random rnd = new Random(); int rndNum = rnd.Next(); //int 取值范围内的随机数 int rndNum = rnd.Ne ...