IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

ASP.NET Discussion :

Titre des fichiers qui change tout seul et suppression ne fonctionne pas


Sujet :

ASP.NET

  1. #1
    Inactif
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2015
    Messages : 2
    Points : 5
    Points
    5
    Par défaut Titre des fichiers qui change tout seul et suppression ne fonctionne pas
    Bonjour, je travaille sur une fonctionnalité permettant de sélectionner plusieurs fichiers les charger et les stocker, le chargement et le stockage des fichiers marche bien ce pandant le fichiers se stockent avec un nom binaire et la supression ne marche pas que doit je faire ?

    Voici mon code
    BlueImpFileUpload.aspx
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
     
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BlueImpFileUpload.aspx.cs" Inherits="BlueImp_BlueImpFileUpload" %>
     
    <!DOCTYPE html>
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <!-- Bootstrap styles -->
        <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
        <!-- Generic page styles -->
        <link rel="stylesheet" href="css/style.css"/>
        <!-- blueimp Gallery styles -->
        <link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css"/>
        <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
        <link rel="stylesheet" href="css/jquery.fileupload.css"/>
        <link rel="stylesheet" href="css/jquery.fileupload-ui.css"/>
        <!-- CSS adjustments for browsers with JavaScript disabled -->
        <noscript>
            <link rel="stylesheet" href="css/jquery.fileupload-noscript.css"/>
        </noscript>
        <noscript>
            <link rel="stylesheet" href="css/jquery.fileupload-ui-noscript.css"/>
        </noscript>
        <style type="text/css">
            body {
                padding-left: 20px !important;
                padding-top: 9px !important;
            }
        </style>
    </head>
    <body>
     
        <div>
            <form id="fileupload" action="server/asp_net/UploadHandler_4_0.aspx" method="POST" enctype="multipart/form-data">
                <!-- Redirect browsers with JavaScript disabled to the origin page -->
                <noscript>
                    <input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"/>
                </noscript>
                <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
                <div class="row fileupload-buttonbar">
                    <div class="col-lg-7">
                        <!-- The fileinput-button span is used to style the file input field as button -->
                        <span class="btn btn-success fileinput-button">
                            <i class="glyphicon glyphicon-plus"></i>
                            <span>Ajouter des fichiers...</span>
                            <input type="file" name="files[]" multiple="multiple"/>
                        </span>
                        <button type="submit" class="btn btn-primary start">
                            <i class="glyphicon glyphicon-upload"></i>
                            <span>Démarrer le chargement</span>
                        </button>
                        <button type="reset" class="btn btn-warning cancel">
                            <i class="glyphicon glyphicon-ban-circle"></i>
                            <span>Anuler le chargement</span>
                        </button>
                        <button type="button" class="btn btn-danger delete">
                            <i class="glyphicon glyphicon-trash"></i>
                            <span>Supprimer</span>
                        </button>
                        <input type="checkbox" class="toggle"/>
                        <!-- The global file processing state -->
                        <span class="fileupload-process"></span>
                    </div>
                    <!-- The global progress state -->
                    <div class="col-lg-5 fileupload-progress fade">
                        <!-- The global progress bar -->
                        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                            <div class="progress-bar progress-bar-success" style="width: 0%;"></div>
                        </div>
                        <!-- The extended global progress state -->
                        <div class="progress-extended">&nbsp;</div>
                    </div>
                </div>
                <!-- The table listing the files available for upload/download -->
                <table role="presentation" class="table table-striped">
                    <tbody class="files"></tbody>
                </table>
            </form>
        </div>
     
        <!-- The template to display files available for upload -->
        <script id="template-upload" type="text/x-tmpl">
            {% for (var i=0, file; file=o.files[i]; i++) { %}
                <tr class="template-upload fade">
                    <td>
                        <span class="preview"></span>
                    </td>
                    <td>
                        <p class="name">{%=file.name%}</p>
                        <strong class="error text-danger"></strong>
                    </td>
                    <td>
                        <p class="size">Processing...</p>
                        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
                    </td>
                    <td>
                        {% if (!i && !o.options.autoUpload) { %}
                            <button class="btn btn-primary start" disabled>
                                <i class="glyphicon glyphicon-upload"></i>
                                <span>Lancer</span>
                            </button>
                        {% } %}
                        {% if (!i) { %}
                            <button class="btn btn-warning cancel">
                                <i class="glyphicon glyphicon-ban-circle"></i>
                                <span>Annuler</span>
                            </button>
                        {% } %}
                    </td>
                </tr>
            {% } %}
        </script>
        <!-- The template to display files available for download -->
        <script id="template-download" type="text/x-tmpl">
            {% for (var i=0, file; file=o.files[i]; i++) { %}
                <tr class="template-download fade">
                    <td>
                        <span class="preview">
                            {% if (file.thumbnailUrl) { %}
                                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                            {% } %}
                        </span>
                    </td>
                    <td>
                        <p class="name">
                            {% if (file.url) { %}
                                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                            {% } else { %}
                                <span>{%=file.name%}</span>
                            {% } %}
                        </p>
                        {% if (file.error) { %}
                            <div><span class="label label-danger">Error</span> {%=file.error%}</div>
                        {% } %}
                    </td>
                    <td>
                        <span class="size">{%=o.formatFileSize(file.size)%}</span>
                    </td>
                    <td>
                        {% if (file.deleteUrl) { %}
                            <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                                <i class="glyphicon glyphicon-trash"></i>
                                <span>Supprimer</span>
                            </button>
                            <input type="checkbox" name="delete" value="1" class="toggle">
                        {% } else { %}
                            <button class="btn btn-warning cancel">
                                <i class="glyphicon glyphicon-ban-circle"></i>
                                <span>Annuler</span>
                            </button>
                        {% } %}
                    </td>
                </tr>
            {% } %}
        </script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
        <script src="js/vendor/jquery.ui.widget.js"></script>
        <!-- The Templates plugin is included to render the upload/download listings -->
        <script src="http://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
        <!-- The Load Image plugin is included for the preview images and image resizing functionality -->
        <script src="http://blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
        <!-- The Canvas to Blob plugin is included for image resizing functionality -->
        <script src="http://blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
        <!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
        <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <!-- blueimp Gallery script -->
        <script src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
        <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
        <script src="js/jquery.iframe-transport.js"></script>
        <!-- The basic File Upload plugin -->
        <script src="js/jquery.fileupload.js"></script>
        <!-- The File Upload processing plugin -->
        <script src="js/jquery.fileupload-process.js"></script>
        <!-- The File Upload image preview & resize plugin -->
        <script src="js/jquery.fileupload-image.js"></script>
        <!-- The File Upload audio preview plugin -->
        <script src="js/jquery.fileupload-audio.js"></script>
        <!-- The File Upload video preview plugin -->
        <script src="js/jquery.fileupload-video.js"></script>
        <!-- The File Upload validation plugin -->
        <script src="js/jquery.fileupload-validate.js"></script>
        <!-- The File Upload user interface plugin -->
        <script src="js/jquery.fileupload-ui.js"></script>
        <!-- The main application script -->
        <script src="js/main.js"></script>
     
    </body>
    </html>
    UploadHandler_4_0.aspx

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
     
    <script language="C#" runat="server">    
     
        private static readonly FilesDisposition FILES_DISPOSITION = FilesDisposition.ServerRoot;
        private static readonly string FILES_PATH = "../../uploads/";
        private static readonly string FILE_QUERY_VAR = "file";
        private static readonly string FILE_GET_CONTENT_TYPE = "application/octet-stream";
     
        private static readonly int ATTEMPTS_TO_WRITE = 3;
        private static readonly int ATTEMPT_WAIT = 100; //msec
     
        private static readonly int BUFFER_SIZE = 4 * 1024 * 1024;
     
        private enum FilesDisposition
        {
            ServerRoot,
            HandlerRoot,
            Absolute
        }
     
        private static class HttpMethods
        {
            public static readonly string GET = "GET";
            public static readonly string POST = "POST";
            public static readonly string DELETE = "DELETE";
        }
     
        [DataContract]
        private class FileResponse
        {
            [DataMember]
            public string name;
            [DataMember]
            public long size;
            [DataMember]
            public string type;
            [DataMember]
            public string url;
            [DataMember]
            public string error;
            [DataMember]
            public string deleteUrl;
            [DataMember]
            public string deleteType;
        }
     
        [DataContract]
        private class UploaderResponse
        {
            [DataMember]
            public FileResponse[] files;
     
            public UploaderResponse(FileResponse[] fileResponses)
            {
                files = fileResponses;
            }
        }
     
        private string CreateFileUrl(string fileName, FilesDisposition filesDisposition)
        {
            switch (filesDisposition)
            {
                case FilesDisposition.ServerRoot:
                    // 1. files directory lies in root directory catalog WRONG
                    return String.Format("{0}{1}/{2}", Request.Url.GetLeftPart(UriPartial.Authority),
                        FILES_PATH, Path.GetFileName(fileName));
     
                case FilesDisposition.HandlerRoot:
                    // 2. files directory lays in current page catalog WRONG
                    return String.Format("{0}{1}{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
                        Path.GetDirectoryName(Request.CurrentExecutionFilePath).Replace(@"\", @"/"), FILES_PATH, Path.GetFileName(fileName));
     
                case FilesDisposition.Absolute:
                    // 3. files directory lays anywhere YEAH
                    return String.Format("{0}?{1}={2}", Request.Url.AbsoluteUri, FILE_QUERY_VAR, HttpUtility.UrlEncode(Path.GetFileName(fileName)));
                default:
                    return String.Empty;
            }
        }
     
        private FileResponse CreateFileResponse(string fileName, long size, string error)
        {
            return new FileResponse()
            {
                name = Path.GetFileName(fileName),
                size = size,
                type = String.Empty,
                url = CreateFileUrl(fileName, FILES_DISPOSITION),
                error = error,
                deleteUrl = CreateFileUrl(fileName, FilesDisposition.Absolute),
                deleteType = HttpMethods.DELETE
            };
        }
     
        private void SerializeUploaderResponse(List<FileResponse> fileResponses)
        {
            DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(UploaderResponse));
     
            Serializer.WriteObject(Response.OutputStream, new UploaderResponse(fileResponses.ToArray()));
        }
     
        private void FromStreamToStream(Stream source, Stream destination)
        {
            int BufferSize = source.Length >= BUFFER_SIZE ? BUFFER_SIZE : (int)source.Length;
            long BytesLeft = source.Length;
     
            byte[] Buffer = new byte[BufferSize];
     
            int BytesRead = 0;
     
            while (BytesLeft > 0)
            {
                BytesRead = source.Read(Buffer, 0, BytesLeft > BufferSize ? BufferSize : (int)BytesLeft);
     
                string aa = source.Read(Buffer, 0, BytesLeft > BufferSize ? BufferSize : (int)BytesLeft).ToString();
                destination.Write(Buffer, 0, BytesRead);
     
                BytesLeft -= BytesRead;
            }
        }
     
        protected void Page_Load(object sender, EventArgs e)
        {
            string FilesPath;
     
            switch (FILES_DISPOSITION)
            {
                case FilesDisposition.ServerRoot:
                    FilesPath = Server.MapPath(FILES_PATH);
                    break;
                case FilesDisposition.HandlerRoot:
                    FilesPath = Server.MapPath(Path.GetDirectoryName(Request.CurrentExecutionFilePath) + FILES_PATH);
                    break;
                case FilesDisposition.Absolute:
                    FilesPath = FILES_PATH;
                    break;
                default:
                    Response.StatusCode = 500;
                    Response.StatusDescription = "Configuration error (FILES_DISPOSITION)";
                    return;
            }
     
            // prepare directory
            if (!Directory.Exists(FilesPath))
            {
                Directory.CreateDirectory(FilesPath);
            }
     
     
            string QueryFileName = Request[FILE_QUERY_VAR];
            string FullFileName = null;
            string ShortFileName = null;
     
            //if (!String.IsNullOrEmpty(QueryFileName))
            if (QueryFileName != null) // param specified, but maybe in wrong format (empty). else user will download json with listed files
            {
                ShortFileName = HttpUtility.UrlDecode(QueryFileName);
                FullFileName = String.Format(@"{0}\{1}", FilesPath, ShortFileName);
     
                if (QueryFileName.Trim().Length == 0 || !File.Exists(FullFileName))
                {
                    Response.StatusCode = 404;
                    Response.StatusDescription = "File not found";
     
                    Response.End();
                    return;
                }
            }
     
            if (Request.HttpMethod.ToUpper() == HttpMethods.GET)
            {
                if (FullFileName != null)
                {
                    Response.ContentType = FILE_GET_CONTENT_TYPE;                   // http://www.digiblog.de/2011/04/android-and-the-download-file-headers/ :)
                    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}{1}", Path.GetFileNameWithoutExtension(ShortFileName), Path.GetExtension(ShortFileName).ToUpper()));
     
                    using (FileStream FileReader = new FileStream(FullFileName, FileMode.Open, FileAccess.Read))
                    {
                        FromStreamToStream(FileReader, Response.OutputStream);
     
                        Response.OutputStream.Close();
                    }
     
                    Response.End();
                    return;
                }
                //else
                //{
                //    List<FileResponse> FileResponseList = new List<FileResponse>();
     
                //    string[] FileNames = Directory.GetFiles(FilesPath);
     
                //    foreach (string FileName in FileNames)
                //    {
                //        FileResponseList.Add(CreateFileResponse(FileName, new FileInfo(FileName).Length, String.Empty));
                //    }
     
                //    SerializeUploaderResponse(FileResponseList);
                //}
            }
            else if (Request.HttpMethod.ToUpper() == HttpMethods.POST)
            {
                List<FileResponse> FileResponseList = new List<FileResponse>();
     
                for (int FileIndex = 0; FileIndex < Request.Files.Count; FileIndex++)
                {
                    HttpPostedFile File = Request.Files[FileIndex];
     
                    string FileName = String.Format(@"{0}\{1}", FilesPath, Path.GetFileName(File.FileName));
                    string ErrorMessage = String.Empty;
     
                    //--- Get required info
                    FileInfo fi = new FileInfo(FileName);
                    string ext = Path.GetExtension(FileName);
                    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(FileName);
                    string uniqueId = Guid.NewGuid().ToString();
                    string uniqueFileName = uniqueId + ext;
                    FileName = String.Format(@"{0}\{1}", FilesPath, uniqueFileName);
     
     
                    for (int Attempts = 0; Attempts < ATTEMPTS_TO_WRITE; Attempts++)
                    {
                        ErrorMessage = String.Empty;
     
                        //if (System.IO.File.Exists(FileName))
                        //{
                        //    FileName = String.Format(@"{0}\{1}_{2:yyyyMMddHHmmss.fff}{3}", FilesPath, Path.GetFileNameWithoutExtension(FileName), DateTime.Now, Path.GetExtension(FileName));
                        //}
     
     
     
     
     
                        try
                        {
                            using (Stream FileStreamWriter = new FileStream(FileName, FileMode.CreateNew, FileAccess.Write))
                            {
                                var inputStream = Request.Files.Get(0).InputStream;
                                FromStreamToStream(inputStream, FileStreamWriter);
                            }
                        }
                        catch (Exception exception)
                        {
                            ErrorMessage = exception.Message;
                            System.Threading.Thread.Sleep(ATTEMPT_WAIT);
                            continue;
                        }
     
                        break;
                    }
     
                    FileResponseList.Add(CreateFileResponse(FileName, File.ContentLength, ErrorMessage));
                }
     
                SerializeUploaderResponse(FileResponseList);
            }
            else if (Request.HttpMethod.ToUpper() == HttpMethods.DELETE)
            {
                bool SuccessfullyDeleted = true;
     
                try
                {
                    File.Delete(FullFileName);
                }
                catch
                {
                    SuccessfullyDeleted = false;
                }
     
                Response.Write(String.Format("{{\"{0}\":{1}}}", ShortFileName, SuccessfullyDeleted.ToString().ToLower()));
            }
            else
            {
                Response.StatusCode = 405;
                Response.StatusDescription = "Method not allowed";
                Response.End();
     
                return;
            }
     
     
            Response.End();
        }   
    </script>
    Fichiers attachés Fichiers attachés

Discussions similaires

  1. Chemin d'accès à un fichier qui change tout seul.
    Par BasicZX81 dans le forum VB.NET
    Réponses: 4
    Dernier message: 25/05/2012, 16h52
  2. Réponses: 3
    Dernier message: 12/11/2008, 18h38
  3. Réponses: 8
    Dernier message: 18/06/2008, 17h56
  4. Variable de session qui change toute seule
    Par mijean dans le forum Langage
    Réponses: 5
    Dernier message: 21/05/2007, 14h42
  5. Ip qui change toute seul , je veux stoper..?
    Par loobstyle dans le forum Windows XP
    Réponses: 2
    Dernier message: 19/06/2006, 08h25

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo