上传文件时找不到文件错误

时间:2014-09-06 07:54:33

标签: c# asp.net custom-controls

我在我的网络应用程序中有一个用于上传多个文件的自定义控件。用户首先选择他的文件,然后按下上传按钮。当用户系统中不存在该文件时,该页面无法加载并出现错误显示未找到的文件。我怎么能抓到这个错误?因为用户可以上传多个文件,如果文件不存在,我想显示错误信息并处理其他文件。这是我的代码

for (int i = 0; i < files.Count; i++)
{
    if (!Directory.Exists(Server.MapPath("~/files/")))
    {
         Directory.CreateDirectory(Server.MapPath("~/files/"));
    }

    HttpPostedFile file = files[i];
    if (!string.IsNullOrEmpty(file.FileName))
    {
        if (file.ContentLength <= 209715200)
        {
            var c = save.NameSave(file);
            fi.path = c;
            fi.title = file.FileName;
            userfiles.Add(fi);
        }
    }   

3 个答案:

答案 0 :(得分:0)

你可以得到用户选择的所有文件路径的数组,然后迭代这样的东西

for(int i = 0 ; i < arr.length ; i++)
 {
    if(!File.Exists(arr[i]))
      {
         //your file do not exist do what ever you want here;
      }
     else
      {
        //your file exists your code for remaining files that exists goes here!
      }
 }

答案 1 :(得分:0)

浏览您上传的每个文件: 以下代码检查目录是否存在,并提供文件写入和读取权限。

foreach (string file in context.Request.Files)
            {
                HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
                string rootPathForwritingfile=AppDomain.CurrentDomain.BaseDirectory +"your destination folder name//"+Uri.UnescapeDataString(Path.GetFileName(hpf.FileName));
                //check for the directory exists or not
                FileStream fileStream = new FileStream(rootPathForwritingfile, FileMode.Create, FileAccess.ReadWrite);
                ReadWriteStream(hpf.InputStream, fileStream);

            }

private static void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = readStream.Read(buffer, 0, Length);
            // write the required bytes
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, Length);
            }
            readStream.Close();
            writeStream.Close();
        }

**

  

使用编辑的上传前检查文件存在的编辑答案   使用Javascript:

**

$('#<%=btnUpload.ClientId%>').click(function(e){
  $.each($('#File1').files,function(index,file){
     if(type of file !== 'undefined' && file.size > 0)
      {
        alert('success');
        //do your stuff
      }
     else
      {
        alert('file not found');
        //do your stuff for breaking the event and warn the user that the file specified was not found.
        //try e.preventdefault();
      }
});
});

答案 2 :(得分:0)

我上传文件的html代码:

<td class="style4" dir="rtl" align="right" 
            style="border: thin ridge #3399FF; direction: ltr; margin-left: 27px;" >
            &nbsp;
            <p id="upload-area" style=" direction: ltr; margin-left: 27px;" align="left" >
<span>File 1 : </span><input id="File1" type="file" size="60" maxlength="209715200" tabindex="0" runat="server" />

</p>
<span id="msg" runat="server"></span>
<input id="btnAddMore" type="button" value="افزودن فایلهای بیشتر" 
onclick="add()"   
                 dir="rtl" 
                style="font-family: Tahoma; font-size: small; background-color: #CC9900;" />
            <br />
<asp:Button ID="btnUpload" runat="server"
            Text="نمایه سازی" onclick="btnUpload_Click" BackColor="#00CC00" 
                Font-Names="Tahoma" Font-Size="10pt" Width="170px" />
            </td>


<script type="text/javascript">
    function add() {
        if (!document.getElementById || !document.createElement)
            return false;

        var uploadArea = document.getElementById("upload-area");

        if (!uploadArea)
            return;

        var newLine = document.createElement("br");
        uploadArea.appendChild(newLine);

        if (!add.lastAssignedId)
            add.lastAssignedId = 2;

        //----------------------------------------------------
        // create new span for fileupload
        var fuSpan = document.createElement('span');
        var fuSpanText = document.createTextNode('File ' + add.lastAssignedId + ' : ');
        fuSpan.appendChild(fuSpanText);
        // create new fileupload control
        var newUploadBox = document.createElement('input');
        // set property for input ( fileupload )
        newUploadBox.type = 'file';
        newUploadBox.size = '60';
        // set other att
        newUploadBox.setAttribute('id', 'FileUpload' + add.lastAssignedId);
        newUploadBox.setAttribute('name', 'FileUpload:' + add.lastAssignedId);
        newUploadBox.setAttribute('maxlength', '209715200');
        newUploadBox.setAttribute('tabindex', add.lastAssignedId);

        //----------------------------------------------------
        // create new span for separator
        var seSpan = document.createElement('span');
        var seSpanText = document.createTextNode(' | ');
        seSpan.appendChild(seSpanText);

        //----------------------------------------------------

        // create new textbox for title
        var newTextBox = document.createElement('input');
        // set property for input ( textbox )
        newTextBox.type = 'text';
        newTextBox.size = '40';
        // set other att
        newTextBox.setAttribute('id', 'txt' + add.lastAssignedId);
        newTextBox.setAttribute('name', 'txt' + add.lastAssignedId);
        newTextBox.setAttribute('tabindex', add.lastAssignedId + 1);

        //----------------------------------------------------

        uploadArea.appendChild(fuSpan);
        uploadArea.appendChild(newUploadBox);



        add.lastAssignedId++;
    }
function btnAddMore_onclick() {

}



</script>