springboot之文件上传下载不得不说的那些坑

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/taiguolaotu/article/details/95945400

之前写过文件上传下载的案例,springboot项目加内置tomct服务器。我是将文件上传到项目下的resources文件夹下的static/upload/img下面。没什么太多的疑问,一般这么写都没问题,下面是我的源代码,没有依依标明注释。简单的介绍下,使用了file类,和类中的方法,以及String的方法也很重要。但是最重要的是**transferTo()**这个方法,它是将文件能够上传上去。

@RestController
@RequestMapping("/SysBase/Device")

public class DeviceController {

	// 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认) 
    public final static String IMG_PATH_PREFIX = "static/upload/img";


	Logger logger = Logger.getLogger(this.getClass().getName());

	@Autowired
	private ZZDeviceService zzDeviceService;

	@RequestMapping(value = "/addZZDevice", method = RequestMethod.POST)
	public SysResult addZZDevice(@RequestParam("file")MultipartFile file,
	HttpServletRequest request, HttpSession session,ZZDevice zzDevice) {
		
		// 构建上传文件的存放 "文件夹" 路径
        String fileDirPath = new String("src/main/resources/" + IMG_PATH_PREFIX);

        File fileDir = new File(fileDirPath);
        if(!fileDir.exists()){
            // 递归生成文件夹
            fileDir.mkdirs();
        }
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        System.out.println(fileDir.getAbsolutePath());
		
		String originalFileName=file.getOriginalFilename();
		String suffix=originalFileName.substring(originalFileName.lastIndexOf("."));
		
        String uuid = UUID.randomUUID().toString();
        String filename = uuid + suffix;
         
         try {
        	// 构建真实的文件路径
             File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
             System.out.println(newFile.getAbsolutePath());

             // 上传图片到 -》 “绝对路径”
             //file.transferTo(newFile.getAbsoluteFile());
             FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
             
             zzDevice.setDeviceImg("/img/"+filename);
             
             try {
     			return this.zzDeviceService.addZZDevice(zzDevice);
     		} catch (Exception e) {
     			e.printStackTrace();
     			return new SysResult(ErrorUtil.CODE5000, e.getMessage(), null);
     		}
             
		} catch (Exception e) {
			e.printStackTrace();
		    logger.info("图片上传失败,出现异常!", e);
		    return new SysResult(ErrorUtil.CODE2001, "图片上传失败", null);
		}
	}

但是值的注意的是,今天项目改成了jetty服务器后,事情就没有我想象的那么简单,同样的代码在进行该操作是就会报出FileNotFoundException:还有卷标什么错误。等于上传的文件前面始终会跟个C盘的目录,这就很难受 下面配图
在这里插入图片描述
那么下面我的解决方式是在pom.xml文件中添加依赖

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

方法也不在使用transferTo()方法,而使用jar包下的类中这个方法进行文件上传即可。
FileUtils.copyInputStreamToFile();

下面把文件下载的代码给大家配上

@RequestMapping(value = "/upload")
	public void upload(@RequestParam("filename")String filename,HttpServletResponse response) {
		 String realPath = new String("D:/file");	
		 File file = new File(realPath);
		 File file1 = new File(file.getAbsolutePath()+"/"+filename);
		 		 
		 try {
			response.setHeader("content-disposition", "attchment;filename="+URLEncoder.encode(filename,"utf-8"));
			try {
				FileUtils.copyFile(file1,response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		 } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

这就是我目前的文件上传和下载,相对简单,希望可以帮助到大家,如有什么不对的对方,还请大家多多指教 谢谢!!!!!!!!!

猜你喜欢

转载自blog.csdn.net/taiguolaotu/article/details/95945400