SpringBoot2.x文件上传实战

2021-06-19 23:06

阅读:702

标签:stack   tle   bst   sub   parameter   system   ppi   form   enc   

设置上传的文件大小:

@Configuration
public class fileConfigure {


    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory=new MultipartConfigFactory();
        //单个文件的大小
        factory.setMaxFileSize("200KB");
        //设置总上传数据的大小
        factory.setMaxRequestSize("1024000KB");
        return factory.createMultipartConfig();
    }


}

Controller:

@RestController
//@PropertySource({"classpath:application.properties"})
public class FileController {


//    @Value("${web.upload-path}")
//    private String filePath;

//    @Autowired
//    private ServiceSetting serviceSetting;

    private String path="C:\\Users\\54701\\Desktop\\images";

    @RequestMapping(value = "uploadfile")
    public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request){

        String name=request.getParameter("name");
        System.out.println("用户名:"+name);

        //获取文件名
        String fileName=file.getOriginalFilename();
        System.out.println("上传的文件名为:"+fileName);

        //获取文件的后缀名
        String suffixName=fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:"+suffixName);

        //文件上传后的路径
        fileName= UUID.randomUUID()+suffixName;
        //File dest=new File(serviceSetting.getName()+fileName);
        File dest=new File(path+fileName);

        try {
            file.transferTo(dest);
            return new JsonData(0,fileName,"上传成功");
        }catch (IllegalStateException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return new JsonData(-1,"fail","上传失败");
    }
}

HTML页面:

DOCTYPE html>
html>
head>
    meta charset="UTF-8" http-equiv="content-type" content="text/html">
    title>图片上传title>
head>
body>
form enctype="multipart/form-data" method="post" action="/uploadfile">
    文件:input type="file" name="head_img"/>
    姓名:input type="text" name="name"/>
    input type="submit" value="上传"/>
form>
body>
html>

 

SpringBoot2.x文件上传实战

标签:stack   tle   bst   sub   parameter   system   ppi   form   enc   

原文地址:https://www.cnblogs.com/Mblood/p/9689862.html


评论


亲,登录后才可以留言!