上载文件时出现“找不到文件”错误

本文关键字:文件 找不到文件 错误 找不到 上载 | 更新日期: 2023-09-27 18:21:04

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

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);
        }
    }   

上载文件时出现“找不到文件”错误

您可以获得用户选择的所有文件路径的数组,然后迭代一些类似的东西

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!
      }
 }

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

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();
      }
});
});