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>