Springboot实现文件上传和获取

Windows版

新建一个properties

# 文件的实体路径
image.path=C:\\Users\\Administrator\\IdeaProjects\\shitang\\img\\

# 待会要获取的IP地址
image.ip=localhost:8080

linux版本

# 文件的实体路径
image.path=/usr/web/shitangdemo/img/

# 待会要获取的IP地址
image.ip=localhost:8000

配置类,让properties的信息获取到这

@Configuration
@PropertySource(value = "file.properties")
public class imgpropertiesConfig implements WebMvcConfigurer {

    @Value("${image.path}")
    public String path;

    private static final String urlPath = "/img/**";

    @Value("${image.ip}")
    public String ip;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler(urlPath).addResourceLocations("file:"+path);
    }
}

提交Controller

@RestController
@CrossOrigin
public class imgController {
    @Autowired
    public imgpropertiesConfig config;

    @Autowired
    public ResponseUtil responseUtil;

    @RequestMapping("/img")
    public String getLocation()
    {
        return config.path;
    }

    @RequestMapping(value = "/addImage",method = RequestMethod.POST)
    public Map<String,Object> returnImg(@RequestPart("file") MultipartFile file,@RequestParam("foodname") String foodname)
    {
        // 获取顺带就把食品名给存进去了
        if(file.isEmpty())
        {
        	//自己创建的UTIL,实际上也就是返回失败的message
            return responseUtil.fileFail();
        }
        else
        {
//              String filePath = config.path+file.getOriginalFilename();
            System.out.println(config.path);
            String filePath = config.path+foodname+".jpg";
            File imgfile = new File(filePath);
            try{
                // 字节流获取
                FileOutputStream stream = new FileOutputStream(imgfile);
                byte[] bytes = file.getBytes();
                stream.write(bytes);
                // 关闭字节流
                stream.close();
                // 返回一个成功的信息和成功的url地址
                return responseUtil.fileSuccess(config.ip+"/img/"+foodname+".jpg");
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return responseUtil.fileFail();
            }
        }
    }
}

你可能感兴趣的:(spring,boot,java,后端)