1

I am using PrimeFaces with JSFin web,and I don't want user upload the same file.That's like you can't save the same file in a path. Is there any way to achieve it?

xmcx
  • 283
  • 3
  • 18

1 Answers1

1

You can't know user's local file path: see this. Also a user could rename or move files, and circumvent the file path check. As Kukeltje commented, better compare file content server-side.

If you really want to validate client-side based on file names, then you could override the widget's validate method. It's undocumented though, so it can go away in future PrimeFaces versions.

<h:form>
    <p:fileUpload mode="advanced" widgetVar="fileup" />
    <script>
        $(function() {
            PF('fileup').validate = function(file) {
                if (file.name === 'alreadyuploaded.png')
                    return 'Not this one though'; // return a error message string
                else
                    return null; // allow
            }
        });
    </script>
</h:form>

I didn't test this in older non-HTML5 browsers though - p:fileUpload in advanced mode works differently in those.

Vsevolod Golovanov
  • 4,068
  • 3
  • 31
  • 65
  • I don't want to know the local file path,i just want want to forbid the name and file type(the suffix) can not add again. – xmcx Jan 23 '18 at 07:18
  • @西门吹雪, amended the answer. – Vsevolod Golovanov Jan 25 '18 at 14:57
  • I have readed your code,and i understand it,but how can i get the "alreadyuploaded.png" real file names(maybe many files),could you explain it more clearly.@Vsevolod Golovanov – xmcx Jan 26 '18 at 14:44
  • @西门吹雪, when a file is uploaded you get a `FileUploadEvent` on the server. Get names with `event.getFile().getFileName()`, store them in some collection in appropriate scope, and `update` the script. The script should refer to the collection (converted to JS) via EL: `if (file.name === #{myBean.forbiddenFilenamesJSList})`... – Vsevolod Golovanov Jan 26 '18 at 16:18
  • But is there any way that users can not add the same file and with suffix.@Vsevolod Golovanov. – xmcx Jan 29 '18 at 03:02