Springboot+文件服务

在Springboot里面实现文件的上传服务

思路:首先ajax那边提交请求上传文件,然后后台进行处理,因为springboot打包之后是个jar包部署,所以希望是在跟jar包同级目录下面创建一个file目录专门来存放文件。

注:这里面使用了Path以及Paths接口工具来做文件的处理,非常的好用以及高效,如果又不懂的请网上查询了解相应的用法等。

下面直接贴代码

    @PostMapping("/api/upload/multi")
    public ResponseEntity uploadFileMulti(
            @RequestParam("extraField") String extraField,
            @RequestParam("files") MultipartFile[] uploadfiles) {
        logger.debug("Multiple file upload!");
        String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename())
                .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
        if (StringUtils.isEmpty(uploadedFileName)) {
            return new ResponseEntity("please select a file!", HttpStatus.OK);
        }
        try {
            saveUploadedFiles(Arrays.asList(uploadfiles));
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity("Successfully uploaded - "
                + uploadedFileName, HttpStatus.OK);
    }
//save file
    private void saveUploadedFiles(List files) throws IOException {

        for (MultipartFile file : files) {

            if (file.isEmpty()) {
                continue; //next pls
            }
            //String appPath = Paths.get(".").getFileSystem()
            byte[] bytes = file.getBytes();
            //Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());

            //Path path = Paths.get("../uploadFileTest/"+file.getOriginalFilename());

            Path path = Paths.get("../uploadFileTest/");
            if(Files.notExists(path)){
                Files.createDirectory(path);
            }
            Path storagePath = Paths.get("../uploadFileTest/"+file.getOriginalFilename());
            Files.write(storagePath, bytes);
        }
    }

因为存放的是相对路径的上一级,所以这面使用了../来到上一级。
下面是html以及ajax





Spring Boot - Multiple file upload example - AJAX







Ajax Post Result

    

js

$(document).ready(function () {
    $("#btnSubmit").click(function (event) {
        //stop submit the form, we will post it manually.
        event.preventDefault();
        fire_ajax_submit();
    });

});

function fire_ajax_submit() {
    // Get form
    var form = $('#fileUploadForm')[0];
    var data = new FormData(form);
    data.append("CustomField", "This is some extra data, testing");
    $("#btnSubmit").prop("disabled", true);
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/api/upload/multi",
        data: data,
        //http://api.jquery.com/jQuery.ajax/
        //https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
        processData: false, //prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        cache: false,
        timeout: 600000,
        success: function (data) {
            $("#result").text(data);
            console.log("SUCCESS : ", data);
            $("#btnSubmit").prop("disabled", false);
        },
        error: function (e) {

            $("#result").text(e.responseText);
            console.log("ERROR : ", e);
            $("#btnSubmit").prop("disabled", false);
        }
    });
}

有什么问题可以底下留言,我看到会及时回复。一起学习一起进步。

你可能感兴趣的:(Springboot+文件服务)