springboot 上传下载

来源:互联网 发布:音频压缩算法开源 编辑:程序博客网 时间:2024/05/17 06:26

项目整体架构:


文件上传:

步骤:

1.建立pom依赖文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.spring</groupId>
    <artifactId>springboot05</artifactId>
    <version>0.0.1-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>


        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.建立application.yml 文件

spring:         
    # HTTP ENCODING  
    http:  
        encoding.charset: UTF-8  
        encoding.enable: true  
        encoding.force: true  
     
    datasource:  
        validation-query: SELECT 1  
        test-on-borrow: true  
          
    mvc:  
        view:  
            prefix: /WEB-INF/test/  
            suffix: .jsp


3.建立上传controller --> uploadController

package com.uploadcontroller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class UploadController {

    /**
     * 单文件上传页面跳转
     *
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value = "/upload")
    public String upload() {
        return "fileupload";
    }

    /**
     * 多文件上传页面跳转
     *
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
    public String batchUpload() {
        return "mutifileupload";
    }

    /**
     * 上传文件,默认存取文件的路径与src 同级
     *
     * @param @param
     *            file
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            try {
                File newFile = new File(file.getOriginalFilename());
                FileOutputStream fileOutputStream = new FileOutputStream(newFile);
                BufferedOutputStream out = new BufferedOutputStream(fileOutputStream);
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败,因为文件是空的.";
        }

    }

    /**
     * 文件上传,指定上传的文件保存的路径
     *
     * @param @param
     *            file
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value = "/upload2", method = RequestMethod.POST)
    @ResponseBody
    public String upload2(@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            // 获取上传的文件名字
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            // 设置保存的路径
            String path = "D:/test";
            File dest = new File(path + "/" + fileName);
            if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
                                                    // dest.getParentFile().mkdir();
                dest.getParentFile().mkdir();
            }
            try {
                file.transferTo(dest);// 保存文件 return "true";
                return "上传文件成功";
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                return "上传文件失败";
            }
        } else {
            return "上传失败,因为文件是空的.";
        }

    }
    
    
    /**
     * 多文件上传
     * @param @param request
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value="multifileUpload",method=RequestMethod.POST)
    @ResponseBody
    public String multifileUpload(HttpServletRequest request){
        
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        
        if(files.isEmpty()){
            return "false";
        }

        String path = "D:/test2" ;
        
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);
            
            if(file.isEmpty()){
                return "文件为空";
            }else{        
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                    
                }catch (Exception e) {
                    e.printStackTrace();
                    return "上传失败";
                }
            }
        }
        return "上传成功";
    }

}

4.建立对应的页面

单文件上传jsp   fileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>文件上传示例</h2>
    <hr />
    <form method="POST" enctype="multipart/form-data" action="/upload2">
        <p>
            文件:<input type="file" name="file" />
        </p>
        <p>
            <input type="submit" value="上传" />
        </p>
    </form>
</body>
</html>


建立多文件上传jsp

mutifileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
    <form action="/multifileUpload" method="post" enctype="multipart/form-data" >
        <p>选择文件1: <input type="file" name="fileName"/></p>
        <p>选择文件2: <input type="file" name="fileName"/></p>
        <p>选择文件3: <input type="file" name="fileName"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
</body>
</html>


5.建立启动类

package com;

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

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

6.运行

右击项目 点击 run As   ==> Maven clear    ====> maven install  

右击项目 点击 run As ===> java application ===》 在浏览器输入:localhost:8080/mybatis


7.注意:文件上传有2种存放路径,一种是默认存储路径在项目src同级目录中,代码详见代码,如图所示

另一种是指定存储路径,代码详见代码,执行效果图如下:


多文件上传效果图看代码执行结果,详见代码;


文件下载:

1.建立pom.xml文件

2.建立application.yml 文件

3.建立文件下载controller -->DownloadController

package com.uploadcontroller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DownloadController {
    
    
    /**
     * 下载文件页面跳转
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping(value = "/down")
    public String upload() {
        return "test";
    }
    
    /**
     * 下载文件
     * @param @param response
     * @param @return
     * @return String
     * @author jiangxueyou
     */
    @RequestMapping("/download")
    public String downLoad(HttpServletResponse response){
        String filename="ceshi.txt";
        String filePath = "D:/test" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

4.建立文件下载中转页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <a href="http://localhost:8080/download">下載txt文件</a>
 </body>
</html>


5.建立启动类

6.运行

右击项目 点击 run As   ==> Maven clear    ====> maven install  

右击项目 点击 run As ===> java application ===》 在浏览器输入:localhost:8080/mybatis


7.执行效果图:




原创粉丝点击