使用springboot上传附件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ethan__xu/article/details/89283535
  • 在pom.xml中添加上传附件依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.3</version>
</dependency>
  • 编写上传附件页面upload.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form name="uploadForm" method="post" action="/upload" enctype="multipart/form-data" >
    <div style="margin: 10px 10px 10px 10px;">
        <input type="file" name="file" multiple value="请选择附件..." title="上传附件" /><br>
        <div style="margin-top: 5px;"></div>
        <input type="submit"value="提交">
    </div>

</form>

</body>
</html>
  • 编写controller
package com.example.springbootdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;


@Controller
public class TestController {
  
    @RequestMapping("/uploadfile")
    public String uploadFile(){
        return "upload";
    }

    @RequestMapping(value="/upload",method = RequestMethod.POST)//MultipartFile,CommonsMultipartFile
    public String upload( MultipartFile file) throws IOException {
        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName:"+file.getOriginalFilename());

        try {
//            File fileDirectory = new File("E:/上传文件/"+new Date().getTime());
//            if(fileDirectory.exists()){
//
//            }else {
//                fileDirectory.mkdirs();
//            }
            //获取输出流
            OutputStream os=new FileOutputStream("E:\\Idea_workspace\\helloworld\\springbootdemo\\uploadfiles\\"+new Date().getTime()+file.getOriginalFilename());
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();

            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
            os.flush();
            os.close();
            is.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "success";
    }
}

  • 示例页面,可以上传多个文件(需要在同一文件夹下)
    在这里插入图片描述
    在这里插入图片描述
    点击提交,跳转到提交成功页面
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ethan__xu/article/details/89283535
今日推荐