Springboot - 파일 업로드(백엔드)

3625 단어 ThymeleafSpringBoot
구성 파일:
// 
#file.uploadFolder=/root/uploadFiles/
// 
file.uploadFolder=d://uploadFiles/

// 
spring.servlet.multipart.max-file-size=50Mb
spring.servlet.multipart.max-request-size=50Mb

 
Controller:
/**
 *

Controller

*

Controller

* @Author MengMeng * @Date 2018/10/25 * @version: 0.1 * @since JDK 1.80_144 */ @Controller @RequestMapping("/file") public class FileController { @Autowired private HttpServletRequest request; @Autowired private FileService fileService; @Value("${file.uploadFolder}") private String uploadFolder; // @RequestMapping(value="/upload/{id}", method = RequestMethod.POST) @ResponseBody public Map uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request,@PathVariable String id) { Map resultMap = new LinkedHashMap(); String contentType = file.getContentType(); // String oldName = file.getOriginalFilename(); //System.out.println(oldName); // , jpeg,png String suffixName = oldName.substring(oldName.lastIndexOf(".")); //System.out.println(" :" + suffixName); // SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss"); String time = df.format(new Date()); String[] Name = oldName.split("\\."); String fileName = time + "-" + Name[0] + suffixName; //System.out.println(fileName); // String filePath = uploadFolder; FileSource filesource = new FileSource(); filesource.setFilename(fileName); fileService.save(filesource,filePath,fileName); try { FileUtil.uploadFile(file.getBytes(), filePath, fileName); //System.out.println(" !"); resultMap.put("status", 200); resultMap.put("message", " !"); } catch (Exception e) { // TODO: handle exception resultMap.put("status", 500); resultMap.put("message", " !"); } // json return resultMap; } }

 
FileServiceImpl:
@Service
public class FileServiceImpl implements FileService {

     @Autowired
     private FileRepository fileRepository;
	
     /**
     *   
     * 

* @author MengMeng * @param filesource * @param filesource * @param fileName * @Date Created date: 2018/10/25 * @return void */ @Override public void save(FileSource filesource, String filePath, String fileName) { // TODO Auto-generated method stub String path = filePath + fileName; filesource.setPath(path); filesource.setId(UUIDUtils.getUUID32()); filesource.setStatus(1); filesource.setUpdatetime(new Date()); fileRepository.save(filesource); } }

 
FileUtil:
/**
 *  spring bean
 * @author MengMeng 
 * Created date: 2018/10/10 
 * @version: 0.1
 * @since JDK 1.80_144
 */
public class FileUtil {

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}

 

좋은 웹페이지 즐겨찾기