springboot成神之——spring的文件上传

本文介绍spring的文件上传

目录结构

配置application

spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB

DemoApplication

package com.springlearn.learn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

WebConfig

package com.springlearn.learn.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
        .allowedHeaders("*");
    }
}

TestController

package com.springlearn.learn.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.springlearn.learn.DemoApplication;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
public class TestController {
    @ResponseBody
    @RequestMapping(value = "/UploadTest", method = RequestMethod.POST)
    public String AuthTest(@RequestParam("file") MultipartFile files, HttpServletRequest request, HttpServletResponse response) {

        String filePath = DemoApplication.class.getResource("").getPath() + "imgupload";

        // Client File Name
        String name = files.getOriginalFilename();
        System.out.println("Client File Name = " + name);

        if (name != null && name.length() > 0) {
            try {
                // Create the file at server
                File serverFile = new File(filePath + File.separator + name);

                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(files.getBytes());
                stream.close();

                System.out.println("Write file: " + serverFile);
            } catch (Exception e) {
                System.out.println("Error Write file: " + name);
            }
        }
        return "上传成功";
    }
}

前端上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <link rel="stylesheet" href="//unpkg.com/iview/dist/styles/iview.css">
    <script src="//unpkg.com/iview/dist/iview.min.js"></script>
</head>
<body>
    <div id="app">
        <Upload 
            :before-upload="handleUpload"
            action=""
        >
            <Button icon="ios-cloud-upload-outline">Upload files</Button>
        </Upload>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                visible: false
            },
            methods: {
                show: function () {
                    this.visible = true;
                },
                handleUpload(file) {
                    let param = new FormData(); 
                    param.append('file',file);
                    let config = {
                        headers:{'Content-Type':'multipart/form-data'}
                    };
                    debugger
                    axios.post('http://localhost:9001/UploadTest', param, config).then(function (response) {
                        console.log(response.data);
                    }).catch(function (error) {
                        console.log(error);
                    }).then(function () {
                    });
                    return false;
                }
            },
            
        })
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/ye-hcj/p/9635810.html