SpringMVC upload and download files

 

<form id="uploadForm" enctype="multipart/form-data">
    <span style="margin-right: 65px;">dictionary name:</span>
    <select class="easyui-combobox" style="width: 180px;" id="batchAddPanelDictConditionSelect" name="dictId">
    </select>    
    <div style="margin-bottom: 20px">
        <input class="easyui-filebox" label="Excel文件:" name="excelFile" id="excelFileId" labelPosition="left"
            data-options="prompt:'Choose a excel file...'" style="width: 100%">
    </div>
</form>

 

function commit() {

    var dictId = $('#batchAddPanelDictConditionSelect').combobox('getValue');
    if (dictId == '') {
        showWarningMessage('Please select a dictionary!');
        return;
    }
    var excelFile = $('#excelFileId').textbox('getValue');
    if (excelFile == '') {
        showWarningMessage('Please select the excel to upload!');
        return;
    }
    var regex = /^.+?(\.xlsx)|(\.xls)$/;
    if (!regex.test(excelFile)) {
        showWarningMessage('The uploaded file must be excel!');
        return;
    }

    var formData = new FormData($('#uploadForm')[0]);

    var options = {
        url: 'entry/batchAddEntries',
        type: 'POST',
        dataType: 'json',
        data: formData,
        // Tell jQuery not to process the sent data
        processData: false,
        // Tell jQuery not to set the Content-Type header
        contentType: false,
        beforeSend: function () {
            console.log("In progress, please wait");
        },
        success: function (rs) {
        },
        error: function (rs) {
        }
    };
    $.ajax(options);
};

 

 

 

@RestController
@RequestMapping(value = { "/entry" })
public class EntryController {
    private static final Logger LOGGER = LoggerFactory.getLogger (EntryController.class);
    /**
     * excel file suffix form 1
     */
    private static final String EXCEL_SUFFIX_01 = ".xls";
    /**
     * excel file suffix form 2
     */
    private static final String EXCEL_SUFFIX_02 = ".xlsx";

    @RequestMapping(value = { "/batchAddEntries" }, method = { RequestMethod.POST })
        public Result<Void> batchAddEntries(@RequestParam("dictId") Integer dictId,
                @RequestParam("excelFile") MultipartFile excelFile) {
            LOGGER.debug("start to batchAddEntries. dictId:{},excelFile:{}", dictId, excelFile);
            checkNotNull(dictId, "dictId is null");
            checkNotNull(excelFile, "excelFile is null");
            String lowcaseName = excelFile.getName().toLowerCase();
            checkArgument(lowcaseName.endsWith(EXCEL_SUFFIX_01) || lowcaseName.endsWith(EXCEL_SUFFIX_02),
                    "upload file is not a excel file");

            // TODO upload excel
            return null;
        }


    @RequestMapping(value = { "/download" }, method = { RequestMethod.GET })
    public ResponseEntity<byte[]> download(HttpServletRequest request,
            @RequestParam("fileName") String fileName) throws Exception {
        // download file path
        String path = request.getServletContext().getRealPath("/static/template/");
        File file = new File(path + File.separator + fileName);
        HttpHeaders headers = new HttpHeaders();
        // Notify the browser to open the image with attachment (download method)
        headers.setContentDispositionFormData("attachment", fileName);
        // application/octet-stream : binary stream data (most common for file downloads).
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
    
}

  

 Reference address:  http://blog.csdn.net/qian_ch/article/details/69258465

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326153479&siteId=291194637