Подтвердить что ты не робот

Выбор и загрузка нескольких файлов

Я использую этот код для загрузки файлов на сервер (в html):

    <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <label>upload file<input type="file" name="file" id="file" /></label>
    <label><input type="submit" name="button" id="button" value="Submit" /></label></form>

Он открывает браузер файлов и позволяет мне выбрать файл, а когда я нажимаю "Отправить", файл отправляется на мой сервер.

Интересно, есть ли способ сделать выбор нескольких файлов.

4b9b3361

Ответ 1

Для этого можно использовать атрибут multiple, например:

<input type="file" multiple />

Чтобы выбрать несколько файлов, вам нужно нажать клавишу Ctrl и нажать на файлы, которые вы хотите добавить.

Ответ 2

Выбор и загрузка нескольких файлов с помощью Spring Framework

В этом сообщении я описываю код сервера и клиентский код для загрузки нескольких файлов.

Следующий код предназначен для упоминания многочастных данных в appContext.xml

appContext.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="20971520"/>
</bean>

Simpleupload.jsp:

script для загрузки нескольких файлов:

<script type="text/javascript">
    var totalsizeOfUploadFiles = 0;
    function getFileSizeandName(input)
    {
        var select = $('#uploadTable');
        for(var i =0; i<input.files.length; i++)
        {           
            var filesizeInBytes = input.files[i].size;
            var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
            var filename = input.files[i].name;
            //alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
            if(i<=4)
            {               
                $('#filetd'+i+'').text(filename);
                $('#filesizetd'+i+'').text(filesizeInMB);
            }
            else if(i>4)
                select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
            totalsizeOfUploadFiles += parseFloat(filesizeInMB);
            $('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
            if(i==0)
                $('#filecount').text("1file");
            else
            {
                var no = parseInt(i) + 1;
                $('#filecount').text(no+"files");
            }                       
        }           
    }

    function CloseAndRefresh() 
    {
        opener.location.reload(true);
        self.close();
    }       
</script>

html дизайн формы:

<body>
<form method="post" id="uploadForm" action="upload" enctype="multipart/form-data">
    <table class="span10">
        <tr>
            <td colspan="3">
                <legend>Simple Upload</legend>
            </td>
        </tr>
        <tr>
            <td>
                <input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
            </td>
        </tr>
        <tr>    
            <td colspan="3">
                <div id="uploaddiv">
                    <table id="uploadTable" class="table table-striped table-bordered">
                        <tr>
                            <th>Title</th>
                            <th>Size</th>
                        </tr>
                        <tbody id="tbodyid">
                            <tr id="tr0">
                                <td id="filetd0" height="10px" width="50px"></td>
                                <td id="filesizetd0" height="10px" width="5px"></td>
                            </tr>
                            <tr id="tr1">
                                <td id="filetd1"></td>
                                <td id="filesizetd1"></td>
                            </tr>
                            <tr id="tr2">
                                <td id="filetd2"></td>
                                <td id="filesizetd2"></td>
                            </tr>
                            <tr id="tr3">
                                <td id="filetd3"></td>
                                <td id="filesizetd3"></td>
                            </tr>
                            <tr id="tr4">
                                <td id="filetd4"></td>
                                <td id="filesizetd4"></td>
                            </tr>                                           
                        </tbody>
                        <tfoot>
                            <tr>
                                <td id="filecount"></td><td id="totalsize"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <button class="btn btn-primary" type="submit" id="startButton" onClick="CloseAndRefresh();">Start</button>
                <button class="btn" id="cancelButton">Cancel</button>
            </td>   
        </tr>
    </table>
</form>

Код UploadController.java:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void UploadReceipts(@RequestParam("files[]") List<MultipartFile> file) throws Exception {
    logger.info(" Inside the upload receipts method "+file.size());
    for(int i=0; i< file.size(); i++)
    {
        if(!file.get(i).isEmpty())
        {
            CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
            logger.info(" Inside the file upload method "+cm.getOriginalFilename());
            simpleUploadService.uploadFileandSaveReceipt(cm);
        }
    }   
}

Ответ 3

если вы используете множественную загрузку файла в форме submit

<input type="file" name="file[]" multiple>

он создает массив файлов и может легко получить имя файла из этого массива.

Ответ 4

Самый простой способ - правильно разместить поля, например:

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<label>upload file<input type="file" name="file[]" id="file1" /></label>
<label>upload file<input type="file" name="file[]" id="file2" /></label>
<label>upload file<input type="file" name="file[]" id="file3" /></label>
<label><input type="submit" name="button" id="button" value="Submit" /></label></form>

Прочитайте это о том, как обрабатывать файлы на стороне сервера.

Однако, если вам нужно что-то лучше, вы должны взглянуть на uploadify.

** Что касается ответа @dotwebs, то атрибут multiple не поддерживается некоторыми браузерами.

Ответ 5

вы можете добавить несколько атрибутов, например:

<input type="file" multiple="true" />