Pergunta

Temos um processo em vigor que carrega arquivos para o nosso site. Tornou -se importante para os usuários poder ver quando esses arquivos foram criados. Estou procurando uma maneira de extrair a data de criação original do httppotedfile. Se alguém tiver uma ideia para mim, eu realmente apreciaria (estou um pouco perplexo neste momento).

Foi útil?

Solução 2

Aqui está a solução com a qual acabei. Depois de enviar o arquivo e salvá -lo no servidor, você pode acessar os metadados no arquivo (essa solução, no entanto, atualmente se aplica apenas a arquivos de imagem - também há algum código extra que poderia ser usado para mostrar todos os metadados para O arquivo, se necessário, e encontrei uma data estranha se formando nos metadados que eu invadi que provavelmente poderia ser feito mais limpo) ...

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

Outras dicas

Você não tem acesso à data em que o arquivo foi criado no cliente. Você pode usar o Fiddler para validar isso. Acredito que os únicos dados que você verá sendo postados é o nome do arquivo e o tipo MIME.

Eu tentei a abordagem mencionada por Bryon acima, mas me dá data incorreta. ou seja, algo por volta do ano 1600.

No entanto, você pode obter a data de cada arquivo (para ser) carregado da propriedade 'LastModifiedDate' através da propriedade de arquivos do FileUpload Control.

Aqui está o exemplo de html/javascript para ele. Eu tirei de:

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_filese modificou um pouco para a nossa necessidade. NOTA: Por favor, leia meu comentário abaixo após este snippet html /javascript.

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

Você pode passar essas informações como um parâmetro adicional usando o controle de upload do arquivo jQuery, por exemplo. Aqui está o link demonstrando o seguinte:

Módulo de upload de arquivo jQuery enviando parâmetro extra

Você acabou de pegar a data de criação do sistema de arquivos no nome HTTPPOSTEDFILE :: FileName.

Algo assim:

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top