一个文件上传模块
<%@ 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"]; var view = Request["v"]; if (string.Compare(view, "edit", true) == 0) { editView.Visible = true; listView.Visible = false; } else { editView.Visible = false; listView.Visible = true; } 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 if (String.Compare(method, "update", true) == 0) { DoUpdate(); } 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.StartsWith(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.StartsWith(clientNo)).Max(ent=>ent.AddTime); if (maxAddTime == null) maxAddTime = new DateTime(2015, 07, 10); 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 DoUpdate() { try { var comm = Request["comment"]; long sessionId = long.TryParse(Request["GroupId"], out sessionId) ? sessionId : 0; Queue.Where(ent => ent.SessionId == sessionId).ToList().ForEach(ent => { ent.Comm = comm; ent.AddTime = DateTime.Now; }); Response.Write(Serializer.Serialize(new BaseResponse<long>() { Code = 0, Msg = "更新成功",Model=sessionId})); } 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("没有文件上传!"); var clientNo = Request["clientNo"]; long sessionId = long.TryParse(Request["GroupId"], out sessionId) ? 0 : sessionId; SaveFile(true,"",clientNo,sessionId); } catch (Exception ex) { var resp = new FilePostResponse() { Code = -1, Msg = Uri.EscapeUriString(ex.Message) }; Response.Write(Serializer.Serialize(resp)); } Response.End(); } private void SaveFile(bool responseflag,String comment,String clientNo,long sessionId) { if (sessionId == 0) { System.Threading.Interlocked.Increment(ref GSessionId); sessionId = GSessionId; } FilePostResponse lastResp = null; for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file.ContentLength <= 0) continue; 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.SessionId = sessionId; resp.Comm=comment; resp.MIME = file.ContentType; resp.Size = file.ContentLength / 1024; resp.ClientNo = 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)); EnQueue(resp); lastResp = resp; } if (lastResp == null) throw new Exception("未保存任何文件!"); if (responseflag) { Response.Write(Serializer.Serialize(lastResp)); } } private static int GFileId = 0; private static long GSessionId = 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;} public String Comm { get; set; } public long SessionId { get; set; } } protected void btnSub_Click(object sender, EventArgs e) { try { lblTips.ForeColor = System.Drawing.Color.Green; lblTips.Text = ""; SaveFile(false,txtComm.Text.Trim(),txtUser.Text.Trim(),0); lblTips.Text = "上传成功!" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } catch (Exception ex) { lblTips.ForeColor = System.Drawing.Color.Red; lblTips.Text = ex.Message; } } </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"; var lastClientNo = "-163343"; $(document).ready(function () { setInterval(queryData, 1000); //上传图片 $("#btnSub").click(function () { var cno = $("#txtUser").val(); if (cno == null || cno == "") { alert("请选填写员工号!"); return false; } setCookie("PostClientNo", cno); return true; }); //保存用户名 $("#btnSaveClientNo").click(function () { var clientNo = $("#clientNo").val(); setCookie("QueryClientNo", clientNo); alert("保存成功!"); }); //加载CientNo var QCNO = getCookie("QueryClientNo"); if (QCNO > "") { $("#clientNo").val(QCNO); clientNoSaved = true; } //加载 CNO var PCNO = getCookie("PostClientNo"); if (PCNO > "") { $("#txtUser").val(PCNO); cnoSaved = true; } }); function queryData() { if ($("#clientNo").size()<=0) { console.log("here"); return; } var clientNo = $("#clientNo").val(); if (clientNo == null || clientNo == "") return; if (clientNo != lastClientNo) { lastClientNo = clientNo; lastUploadTime = "2015-07-10" $("#panelShow").html(""); } 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)); } }); } //cookie method function setCookie(name, value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); } //读取cookies function getCookie(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; } </script> </head> <body> <form id="form1" runat="server"> <div class="page"> <div class="header"> <div class="title"> <h1> 手机PC文件传输 </h1> </div> <div class="loginDisplay"> [ <a href="#" style="display:none" id="HeadLoginView_HeadLoginStatus">登录</a> ] </div> <div class="clear hideSkiplink"> </div> </div> <asp:Panel ID="editView" runat="server"> <div class="main"> 用 户:<asp:TextBox ID="txtUser" runat="server"></asp:TextBox><br /> 文件1:<asp:FileUpload ID="FileUpload1" runat="server" /><br /> 文件2:<asp:FileUpload ID="FileUpload2" runat="server" /><br /> 文件3:<asp:FileUpload ID="FileUpload3" runat="server" /><br /> 文件4:<asp:FileUpload ID="FileUpload4" runat="server" /><br /> 备 注:<br /> <asp:TextBox ID="txtComm" runat="server" Height="85px" TextMode="MultiLine" Width="222px"></asp:TextBox> <br /> <asp:Button ID="btnSub" runat="server" Text="提交" onclick="btnSub_Click" /> <a href="FilePost.aspx">返回</a> <asp:Label ID="lblTips" runat="server" Font-Size="12pt" Text="..."></asp:Label> <br /> </div> </asp:Panel> <asp:Panel ID="listView" runat="server"> <div class="main"> <h2> FILE POST </h2> <div> <a href="?v=edit">上传</a> <br /> <input type="text" id="clientNo" value="" /><input id="btnSaveClientNo" type="button" value="保存用户名" /> <br /><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: 10%"> 用户 </td> <td style="width: 18%"> 文件名 </td> <td style="width: 15%; text-align: center"> 类型 </td> <td style="width: 15%; text-align: center"> 时间 </td> <td style="width: 28%; text-align: center"> 注释 </td> <td style="text-align: center"> 组号 </td> <td style="text-align: center"> </td> </tr> </HeaderTemplate> <ItemTemplate> <tr style="background-color: White;"> <td> <%#Eval("ClientNo") %> </td> <td> <a href='FilePost.aspx?m=download&FId=<%#Eval("FileId") %>' target="_blank"><%#Eval("Name") %></a> </td> <td style="text-align: center"> <%#Eval("MIME")%> </td> <td style="text-align: center"> <%# ((DateTime)Eval("AddTime")).ToString("MM-dd HH:mm:ss")%> </td> <td style="text-align: center"> <%#Eval("Comm")%> </td> <td style="text-align: center"> <%#Eval("SessionId")%> </td> <td style="text-align: center"> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div> <div id="tips"></div> </div> </asp:Panel> <div style="text-align:center"> <img src="102.jpeg" alt="FilePost" /> </div> <div class="clear"> </div> </div> <div class="footer"> </div> </form> </body> </html>
package cn.fstudio.filepost; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.UUID; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; import cn.fstudio.util.PreferencesUtils; import cn.fstudio.util.StringUtil; import android.R.integer; 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; Button btnSaveCNo = null; Button btnSaveComment=null; EditText txtComment = null; EditText txtUrl = null; EditText txtNo = null; EditText txtGroupId=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); } } if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { ArrayList<Uri> imageUris = intent .getParcelableArrayListExtra(Intent.EXTRA_STREAM); UploadFile(imageUris); Log.d("T", ""); } } private void initView() { txtGroupId=(EditText)findViewById(R.id.txtSessionId); txtGroupId.setText("0"); txtNo = (EditText) findViewById(R.id.txtNo); txtComment = (EditText) findViewById(R.id.txtComment); btnSaveComment=(Button)findViewById(R.id.btnPost); btnSaveComment.setOnClickListener(this); btnSaveCNo = (Button) findViewById(R.id.button2); btnSaveCNo.setOnClickListener(this); 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(ArrayList<Uri> uris) { String ip = txtUrl.getEditableText().toString(); String clientNo = txtNo.getText().toString(); String url = "http://" + ip + "/filePost.aspx?m=upload&ClientNo=" + clientNo; Log.d("T", url); ArrayList<String> filePathList = new ArrayList<String>(); for (int i = 0; i < uris.size(); i++) { /* 处理 媒体 Uri类型 */ Uri uri = uris.get(i); String file_path = ""; 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); filePathList.add(file_path); actualimagecursor.close(); } else { file_path = uri.getPath(); filePathList.add(file_path); } } /* 上传文件参数 */ RequestParams requestParams = new RequestParams(); for (int i = 0; i < filePathList.size(); i++) { String fpath = filePathList.get(i); Log.i("T", "file_path" + fpath); File file = new File(fpath); try { requestParams.put("file" + i, file); } catch (FileNotFoundException e) { Log.d("T", e.getMessage()); } } AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(1000 * 60); client.post(url, requestParams, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { try { JSONObject jsonObject=new JSONObject(responseString); long groupId= jsonObject.getLong("SessionId"); txtGroupId.setText(String.valueOf( groupId)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT) .show(); Log.d("T", responseString); } @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(int statusCode, Header[] headers, String responseString, Throwable throwable) { String msg = throwable.getMessage(); if (msg == null) msg = ""; Log.d("T", msg); Toast.makeText(MainActivity.this, "上传失败!" + "\r\n" + msg, Toast.LENGTH_SHORT).show(); } }); } 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.setTimeout(1000 * 60); client.post(url, requestParams, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { try { JSONObject jsonObject=new JSONObject(responseString); long groupId= jsonObject.getLong("SessionId"); txtGroupId.setText(String.valueOf( groupId)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT) .show(); Log.d("T", responseString); } @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(int statusCode, Header[] headers, String responseString, Throwable throwable) { String msg = throwable.getMessage(); if (msg == null) msg = ""; Log.d("T", msg); Toast.makeText(MainActivity.this, "上传失败!" + "\r\n" + msg, Toast.LENGTH_SHORT).show(); } }); } /* 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(); } else if (arg0.getId() == R.id.button2) { String cNo = txtNo.getText().toString(); PreferencesUtils.setStringPreferences(getApplicationContext(), "ClientNo", cNo); Toast.makeText(this, "用户编号已经保存", Toast.LENGTH_SHORT).show(); } else if (arg0.getId() == R.id.btnPost) { AttchComment(); } } private void AttchComment() { // TODO Auto-generated method stub String ip = txtUrl.getEditableText().toString(); String groupId=txtGroupId.getText().toString(); if(StringUtil.isNullOrEmpty(groupId)){ return; } String url = "http://" + ip + "/filePost.aspx?m=update&GroupId=" + groupId; RequestParams requestParams = new RequestParams(); requestParams.put("comment", txtComment.getText()); AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(1000 * 60); client.post(url,requestParams, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { try { JSONObject jsonObject=new JSONObject(responseString); long groupId= jsonObject.getLong("SessionId"); txtGroupId.setText(String.valueOf( groupId)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(MainActivity.this, "备注附加成功!", Toast.LENGTH_SHORT) .show(); Log.d("T", responseString); } @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(int statusCode, Header[] headers, String responseString, Throwable throwable) { String msg = throwable.getMessage(); if (msg == null) msg = ""; Log.d("T", msg); Toast.makeText(MainActivity.this, "上传失败!" + "\r\n" + msg, Toast.LENGTH_SHORT).show(); } }); } }