zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    Shell入门教程:命令替换 $() 和 ``
    CentOS启用sudo,禁用root远程登录
    .htaccess 基础教程(四)Apache RewriteCond 规则参数
    .htaccess 基础教程(三)RewriteCond标志符,RewriteRule适用的标志符
    .htaccess 基础教程(二)
    .htaccess 基础教程(一)
    phpMyAdmin 个性化设置,字体大小设置,去掉“以树形显示数据库”,禁用“发送错误报告”
    PHP的$_SERVER['PHP_SELF']造成的XSS漏洞攻击及其解决方案
    PHP变量作用域(花括号、global、闭包)
    获取PHP文件绝对地址$_SERVER['SCRIPT_FILENAME'] 与 __FILE__ 的区别
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/9635810.html
Copyright © 2011-2022 走看看