Pregunta

Tenemos un proceso en el lugar que carga los archivos a nuestro sitio web. Se ha convertido en importante para los usuarios a ser capaz de ver cuando se crearon los archivos. Estoy buscando una manera de extraer la fecha de creación original de la HttpPostedFile. Si alguien tiene una idea para mí yo realmente apreciaría (Estoy un poco perplejo en este punto).

¿Fue útil?

Solución 2

Aquí está la solución que terminó con. Una vez que haya subido el archivo y lo ha guardado en el servidor puede acceder a los metadatos en el archivo (esta solución, sin embargo, sólo se aplica actualmente a los archivos de imagen - también hay algo de código extra en allí que podría ser utilizado para mostrar todo el metadatos para el archivo si es necesario, y me encontré con algunos formateo fecha raro en los metadatos que han pirateado en torno a que probablemente se podría hacer más limpia) ...

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(UPLOAD_DIRECTORY + file.FileName);
                if (!fileInfo.Exists)
                {
                    break;
                }
                else
                {

                  //Check for metadata original create date
                  if (_imageFormats.Contains(fileInfo.Extension.ToLower()))
                  {
                    Stream fileStream = fileInfo.OpenRead();
                    System.Drawing.Image image = new System.Drawing.Bitmap(fileStream);

                    // Get the PropertyItems property from image.
                    System.Drawing.Imaging.PropertyItem[] propItems = image.PropertyItems;

                    // For each PropertyItem in the array, display the ID, type, and 
                    // length.
                    int count = 0;
                    string s1 = null;
                    string dateID = null;
                    foreach (System.Drawing.Imaging.PropertyItem propItem in propItems)
                    {
                      s1 += "Property Item " + count.ToString() + "/n/r";

                      s1 += "iD: 0x" + propItem.Id.ToString("x") + "/n/r";
                      if (("0x" + propItem.Id.ToString("x")) == PROPERTYTAGEXIFDTORIG)
                      {
                        dateID = count.ToString();
                      }
                      s1 += "type: " + propItem.Type.ToString() + "/n/r";

                      s1 += "length: " + propItem.Len.ToString() + " bytes" + "/n/r";

                      count++;
                    }
                    // Convert the value of the second property to a string, and display 
                    // it.
                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                    if (dateID != null)
                    {
                      string date = encoding.GetString(propItems[int.Parse(dateID)].Value);
                      date = date.Replace("\0", string.Empty);
                      string[] datesplit = date.Split(' ');
                      string newDate = datesplit[0].Replace(":", "-") + " " + datesplit[1];
                      originalCreateDate = DateTime.Parse(newDate);
                    }
                    fileStream.Close();
                  }

Otros consejos

Usted no tiene acceso a la fecha de creación del archivo en el cliente. Se puede utilizar Fiddler para validar esto. Creo que los únicos datos que se verá publicado es el nombre de archivo y el tipo MIME.

He probado el enfoque mencionado por Bryon anterior, pero me da fecha incorrecta. es decir algo en torno al año 1600.

Sin embargo, puede obtener la fecha para cada uno (siendo) subido archivo de la propiedad 'LastModifiedDate' a través de la propiedad de los archivos de control FileUpload.

Aquí está el ejemplo HTML / Javascript para ello. Lo he tomado de:

http://www.w3schools.com/jsref/tryit.asp ? archivo = tryjsref_fileupload_files y modificado un poco para nuestra necesidad. Nota:. Por favor, lea mi comentario a continuación después de este código HTML / Javascript fragmento

<!DOCTYPE html>
<html>
<body onload="myFunction()">

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

<p id="demo"></p>

<script>
function myFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in myFile) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "<br>";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes <br>";
                }
                if ('lastModifiedDate' in file) {
                    txt += "lastModifiedDate: " + file.lastModifiedDate.toString();
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

</body>
</html>

Puede pasar esta información como un parámetro adicional usando jQuery de control de carga de archivos, por ejemplo. Aquí está el enlace que demuestra esto:

jQuery archivo de módulo de carga extra de envío de parámetros

Usted acaba de agarrar la fecha de creación del sistema de archivos de la HttpPostedFile :: Nombre de archivo.

algo como esto:

HttpFileCollection MyFileColl = Request.Files;
HttpPostedFile MyPostedFile = MyFileColl.Get(0);
String filename = MyPostedFile.FileName;
String creationTime;

if (File.Exists(fileName)) 
{
      creationTime = File.GetCreationTime(fileName).ToString(); 
}
System.writeLine(creationTime);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top