简体   繁体   English

ASP.NET 和 C# 文件上传

[英]ASP.NET and C# FileUpload

I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if yes then it would just override the current picture with the new one but if not then just leave it alone. How can I do this?. Right now I have this. Also if the solution is in javascript I could also use that (but i am not too good with javascript:) ) Thank you I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if是的,那么它只会用新的图片覆盖当前图片,但如果不是,那就别管它了。我该怎么做?现在我有这个。另外,如果解决方案在 javascript 中,我也可以使用它(但我我不太喜欢 javascript :) ) 谢谢

<div class="style">
Choose an Image:&nbsp;<asp:FileUpload ID="getImage" runat="server" Width="150px" BorderStyle="Inset" EnableViewState="true" />
 <asp:RegularExpressionValidator ID="RegularExpressionValidator"
runat="server" ControlToValidate="getImage" CssClass="Error" Display="dynamic" ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])" ErrorMessage="Select a correct file format"></asp:RegularExpressionValidator>
</div>

Please be aware I am a total newbie with Javascript so if that is what's going to work please explain as if I was a 5 year old.请注意,我是 Javascript 的新手,所以如果这行得通,请像我 5 岁一样解释。

I really appreciate the help.我真的很感激帮助。

Add the code below to your submit button将下面的代码添加到您的提交按钮

OnClientClick="return confirm('Are you sure you want to delete this file?')"

Edit as someone pointed out this will ask this question without taking in concern previous file and new one.正如有人指出的那样进行编辑,这将在不考虑以前的文件和新文件的情况下提出这个问题。 It will do basic job.它将完成基本工作。

My question is whether you doing this for edit mode or in new item mode.我的问题是你是在编辑模式还是在新项目模式下这样做。 I mean are you editing item or adding new one on page you are interested to check?我的意思是您是在编辑项目还是在您有兴趣检查的页面上添加新项目?

My solution will perform the check just before postback.我的解决方案将在回发之前执行检查。 I also use jquery a little bit.我也用了一点jquery。

The important piece of the puzzle here is retrieving the previous file name.这里的难题的重要部分是检索以前的文件名。 I created a PageMethod to do this part.我创建了一个 PageMethod 来完成这部分工作。 So in my aspx.cs file I have a function that looks like this:所以在我的 aspx.cs 文件中,我有一个看起来像这样的 function:

using System.Web.Services;

.......

[WebMethod()]
public static string GetPreviousFileName()
{
    //put logic here to get the filename to compare against.
    return "somefilename.ext";
}

You'll need to implement your own logic for how to retrieve the file name.您需要实现自己的逻辑来检索文件名。 Another, simpler but less flexible, approach for handling the previous file name would be to add an asp:hiddenfield to your page and populate it with the name of the previous file on page load.另一种更简单但不太灵活的处理前一个文件名的方法是在页面中添加一个 asp:hiddenfield 并在页面加载时使用前一个文件的名称填充它。 Then you could compare by reading $('#<%= hiddenField.ClientID %>').val() .然后您可以通过阅读$('#<%= hiddenField.ClientID %>').val()进行比较。

Next I used the following code for my file upload control and a submit buton:接下来,我将以下代码用于文件上传控件和提交按钮:

<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
<div>
    <asp:FileUpload ID="fu" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClientClick="return checkDuplicateFile();" Text="Upload File" />
</div>

Two important things to note here: The ScriptManager has EnablePageMethods="true" and the asp:button has an OnClientClick attribute specified.这里需要注意两件重要的事情:ScriptManager 具有EnablePageMethods="true"并且 asp:button 具有指定的 OnClientClick 属性。 Lastly, the javascript part of the solution which retrieves the value from the page method and and compares the file names:最后,解决方案的 javascript 部分从页面方法检索值并比较文件名:

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var oFilename = "";

    $(function () {
        //get original file name on page load
        PageMethods.GetPreviousFileName(function (result) {
            oFilename = result;
        });
    });

    function checkDuplicateFile() {
        var newVal = $('#<%=fu.ClientID %>').val();
        var newValFile = newVal.substr(newVal.lastIndexOf("\\") + 1);

        //returning true causes postback, returning false stops postback.
        if (newValFile == oFilename) { return confirm("This image name already exists, do you want to replace it?"); }
        else return true;
    }
</script>

Couple of things going on here.这里发生了几件事。 We use our pagemethod to pull in our old filename from the page method on page load ( PageMethods.GetPreviousFileName ).我们使用 pagemethod 从页面加载时的 page 方法中提取旧文件名( PageMethods.GetPreviousFileName )。 Next we setup the function which will be called by our buttons onClick event (client side).接下来我们设置 function 将由我们的按钮 onClick 事件(客户端)调用。 The <%=fu.ClientID %> snippet of code will output the client side id of the file upload control for use in our javascript. <%=fu.ClientID %>代码片段将 output 文件上传控件的客户端 ID 用于我们的 javascript。 I do a substring on the file path and extract the file name by pulling back only the text after the last '\' and do the compare.我在文件路径上执行 substring 并通过仅拉回最后一个“\”之后的文本来提取文件名并进行比较。

As my comment in the function says, returning true/false from a function called in the OnClientclick event determines whether a post back occurs.正如我在 function 中的评论所说,从 OnClientclick 事件中调用的 function 返回 true/false 确定是否发生回发。 So if the user clicks yes in the confirmation box then a postback occurs, else if they click no then none occurs.因此,如果用户在确认框中单击“是”,则会发生回发,否则如果他们单击“否”,则不会发生。

Hope that at least gets you going in the right direction.希望至少能让你朝着正确的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM