编程语言
首页 > 编程语言> > java springboot实现图片上传服务器

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("错误");
        }
    }

最后看结果,此处把本机当成服务器,如图:
在这里插入图片描述
初始没有文件,postman发送请求上传文件后,如图:
在这里插入图片描述
结果:
在这里插入图片描述

标签:HttpServletRequest,java,springboot,uploadFile,void,request,folder,上传
来源: https://blog.csdn.net/fengzi_big/article/details/121718089