004 springboot文件上传

  关于文件上传,在spring cloud会再经过配置文件的处理,在spring boot则不需要,在这里写一个文件上传的接口。

  单文件上传,如果以后写多文件上传再进行补充。

1.文件目录

  

 

2.控制器程序

package com.jun.file.controller;

import com.jun.file.service.UpLoadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UpLoadFileController {
    @Autowired
    private UpLoadFileService upLoadFileService;
    @PostMapping("/upload/img")
    public String uploadImg(@RequestParam("file") MultipartFile file){
        int count=upLoadFileService.upLoadImg(file);
        return "success";
    }

}

 

3.服务方法

package com.jun.file.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 这个类用于文件的上传
 */
@Service
public class UpLoadFileService {
    public int upLoadImg(MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        fileName = name+suffixName;
        String path = "E:/javaImg/test/";
        String path_img = path+fileName;
        File dest = new File(path_img);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

  

4.测试

  

 

 

 

转载于:https://www.cnblogs.com/juncaoit/p/11188765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值