spring boot 上传文件

版权声明:本文为博主原创文章,转载注明出处。有需要请联系[email protected] https://blog.csdn.net/weixin_42749765/article/details/84786717

上传重点思路:

    1、为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放于WEB-INF目录下。

  2、为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名。

  3、为防止一个目录下面出现太多文件,要使用hash算法打散存储。

  4、要限制上传文件的最大值。

  5、要限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法。

java 代码:

package com.supermap.file;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.supermap.uitl.DateTimeUitl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpSession;

/**
 * 文件上传类
 * 
 * @author yushen
 *
 */
@Controller
public class UploadController {
	
	/**
	 * 创建日志
	 * 
	 */
    private static final Log LOGGER = LogFactory.getLog(UploadController.class);
    
    //获取基础文件服务路径地址(入服务器id,服务器文件服务路径)0代表第一个太文件服务器
    private static final String Basicspath = "/tem/Imagelserver/0/";	
    
    /**
     * 文件上传方法
     * 
     * @param file
     * @param session
     * @return
     */
    @RequestMapping("/2/Upload")
    @ResponseBody
    public String Upload(@RequestParam("file") MultipartFile file,HttpSession session) {
    	//通过session 获取用户的id 生成用户id库路径
        Integer user = (Integer) session.getAttribute("user");
        if(user == null) {
        	return "上传失败,没有用户信息!";
        }
        
    	//记录日志
    	LOGGER.info(new StringBuffer("用户id:"+user)+"开始上传文件!");
    	
    	//文件判断为空
    	if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
    	
    	//获取文件原始名称
        String fileOriginalName = file.getOriginalFilename();
        //设置文件前缀
        String fliePrefix = "";
        //设置文件后缀
        String fileSuffix = "";
        
        //校验文件名安全性
        if(fileOriginalName.indexOf(".") != -1) {//判断事包含带有结尾符的文件
        	//只支持上传jpg和png格式文件图片
        	if(fileOriginalName.split("\\.")[1].equals("png") || fileOriginalName.split("\\.")[1].equals("jpg")) {
        		fliePrefix = UUID.randomUUID().toString().replace("-", "");
        		fileSuffix = fileOriginalName.split("\\.")[1];
        	} else {
        		return "上传失败,上传文件类型不是png和jpg格式!";
        	}
        }
        
        //系统设置路径
        String newfilePath = DateTimeUitl.nowTimeA +"/" + user + "/" ;
        //唯一服务地址
        String newfilePathOnly = Basicspath +newfilePath;
        
        
        //判断地址是否存在
        File fileUIS = new File(newfilePathOnly);  
        if(!fileUIS.exists()){//如果不存在文件夹创建文件夹
        	fileUIS.mkdirs();  
        } 
        
        //设置文件载入到的地址
        File dest = new File(newfilePathOnly + fliePrefix + fileSuffix);
        try {
            file.transferTo(dest);
            LOGGER.info("文件:"+fliePrefix + fileSuffix+"上传成功");
            return "上传成功,文件地址:" + newfilePath + fliePrefix + fileSuffix;
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上传失败!";
    }

}

jsp代码

<!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>
</head>
<body>
    <form action="http://localhost:8080/2/serviceUpload" 
    enctype="multipart/form-data"  method="POST" >
        上传文件:<input type="file" name="file"/><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

pom.xml 不需要引入特别的包

猜你喜欢

转载自blog.csdn.net/weixin_42749765/article/details/84786717