Springboot 文件上传下载

做一个app更新的文件管理中心



    4.0.0

    com.dalaoyang
    springboot_upload_download
    0.0.1-SNAPSHOT
    jar

    springboot_upload_download
    springboot_upload_download

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            net.sourceforge.nekohtml
            nekohtml
            1.9.15
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
            mysql
            mysql-connector-java
        

        
            com.mchange
            c3p0
            0.9.5.2
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

package com.source.controller;

import com.source.entity.ApkUpdate;
import com.source.service.ApkUpdateService;
import com.source.utils.DateUtil;
import com.source.utils.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * @author source
 * @Description
 * @project springboot_learn
 * @package com.source.controller
 * @email [email protected]
 * @date 2018/4/9
 */
@Slf4j
@RestController
public class FileController {

    @Autowired
    private ApkUpdateService apkUpdateService;

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            fileName = String.valueOf(System.currentTimeMillis())+fileName.substring(fileName.lastIndexOf("."),fileName.length());
            log.info("上传的文件名为:" + fileName);
            //设置文件存储路径
            String filePath = SysConfig.UPLOADPATH;
            String path = filePath + fileName;
            String ServerUrl = request.getServerName()+":"+request.getServerPort()+"/download?fileName=";
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            Map parameterMap = getParameterMap(request);
            ApkUpdate apkUpdate = new ApkUpdate();
            apkUpdate.setProjectId(Integer.parseInt(parameterMap.get("projectId").toString()));
            apkUpdate.setVersionCode(Integer.parseInt(parameterMap.get("versionCode").toString()));
            apkUpdate.setVersionName(parameterMap.get("versionName").toString());
            apkUpdate.setRemark(parameterMap.get("versionName").toString());
            apkUpdate.setAddress(ServerUrl+fileName);
            apkUpdate.setStates(1);
            apkUpdate.setCounts(0);
            apkUpdate.setReleaseTime(DateUtil.getDateTime());
            apkUpdateService.insertApkUpdate(apkUpdate);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @PostMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) {
        List files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = SysConfig.UPLOADPATH;
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + file.getOriginalFilename())));//设置文件路径及名字
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "第 " + i + " 个文件上传失败 ==> "
                            + e.getMessage();
                }
            } else {
                return "第 " + i
                        + " 个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = request.getParameter("fileName");// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File(SysConfig.UPLOADPATH+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
   /**
     * 从request中获得参数Map,并返回可读的Map
     *
     * @param request
     * @return
     */
    public static Map getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i

你可能感兴趣的:(Springboot 文件上传下载)