Home Springboot功能模块 Springboot 上传文件坑点

Springboot 上传文件坑点

先附上上传工具类源码:

package com.southwind.mmall002.controller.file;

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

import java.io.File;
import java.io.IOException;

/**
* @Description
* @Author sgl
* @Date 2018-05-15 14:04
*/
@Controller
public class UploadController {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

@GetMapping(“/upload”)
public String upload() {
return “upload”;
}

@PostMapping(“/upload”)
@ResponseBody
public String upload(@RequestParam(“file”) MultipartFile file) {
if (file.isEmpty()) {
return “上传失败,请选择文件”;
}

String fileName = file.getOriginalFilename();
//此处必须填写绝对路径!!!
String filePath = “C:\\Users\\橙汁\\Desktop\\mmall09.1 -5.14.03\\src\\main\\resources\\static\\images\\”;
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
LOGGER.info(“上传成功”);
return “上传成功”;
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return “上传失败!”;
}

}

注意点:

yml文件中配置文件上传的大小
上传工具类必须写绝对路径!!!

 

 

——————-5.15更新——————

设置绝对路径之后第二天重启项目还是找不到路径

原因是项目更改了名称,绝对路径也要跟着更改,另外C:\\Users\\橙汁\\Desktop\\mmall09.1 -5.14.03\\src\\main\\resources\\static\\images\\ 

最后的\\不要掉!!!

发表评论

发表评论