java springboot实现图片上传服务器

java springboot实现图片上传服务器


话不多说,直接上代码:

controller层

/**
     * 上传应用图标文件
     * @param uploadFile
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    public void uploadFile(@RequestParam(value = "file",required = true) MultipartFile uploadFile,
                         HttpServletRequest request) {
         firstService.uploadFile(uploadFile,request);

    }

service层


import com.trs.dto.Boo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * Demo class
 *
 * @author crazy-water
 * @date 11/27/2021 18:23
 */
public interface FirstService {
    void isNull(Boo boo);

    void uploadFile(MultipartFile uploadFile, HttpServletRequest request);
}

serviceImpl层

@Override
    public void uploadFile(MultipartFile uploadFile, HttpServletRequest request) {
        File folder = new File("D:/Download/");
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名,避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() +uploadFile+ newName;

        } catch (IOException e) {
            throw new RuntimeException("错误");
        }
    }

最后看结果,此处把本机当成服务器,如图:
java springboot实现图片上传服务器
初始没有文件,postman发送请求上传文件后,如图:
java springboot实现图片上传服务器
结果:
java springboot实现图片上传服务器

上一篇:SpringMVC_04重定向和转发


下一篇:微服务01(Eureka、Nacos)