当前位置:
首页 >
保证文件名的唯一性
发布时间:2025/3/20
45
豆豆
在项目开发中,经常会有文件上传和下载的功能,上传的文件会保存在指定的地方,比如,mongodb数据库中、FTP文件服务器中、或者保存在某个路径下,需要保证上传文件名称的唯一性
一般的方法就是使用时间戳、或者使用GUID
这里,在上传文件时,命名使用的是获取当前日期时间+Session的ID+文件名称
比如,上传文件“文档信息.txt”,效果如下
前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebDropzone.WebForm" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"><meta name="viewport" content="width=device-width" /><title></title> </head> <body><form id="form1" runat="server"><div><table style="width: 343px"><tr><td style="width: 100px">文件上传判断</td><td style="width: 100px"></td></tr><tr><td style="width: 100px"><asp:FileUpload ID="FileUpload1" runat="server" Width="400px" /></td><td style="width: 100px"><asp:Button ID="Button1" runat="server" OnClick="bt_upload_Click" Text="上传"/></td></tr><tr><td style="width: 100px"><asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td><td style="width: 100px"></td></tr></table></div></form> </body> </html>后台代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.UI.WebControls;namespace WebDropzone {public partial class WebForm : System.Web.UI.Page, IHttpHandler{protected void Page_Load(object sender, EventArgs e){}protected void bt_upload_Click(object sender, EventArgs e){try{if (FileUpload1.PostedFile.FileName == ""){this.lb_info.Text = "请选择文件!";}else{string filepath = FileUpload1.PostedFile.FileName;string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);string serverpath = Server.MapPath("File/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;FileUpload1.PostedFile.SaveAs(serverpath);this.lb_info.Text = "上传成功!";}}catch (Exception error){this.lb_info.Text = "上传发生错误!原因:" + error.ToString();}}} }关键代码,就两句如下
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); string serverpath = Server.MapPath("File/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;如果,这样也可能重复的话,可以在文件名中再添加GUID
总结
- 上一篇: 检查文件类型
- 下一篇: Tomcat启动一闪而过