springboot 简单的文件上传

本文详细介绍了在Spring MVC中处理文件上传时遇到的路径问题,包括相对路径与绝对路径的区别,如何处理静态资源路径,以及如何确保文件正确保存。在上传过程中,检查了文件大小和类型,并提供了文件保存的实现步骤。注意,项目中通常使用相对路径以保持可移植性,同时指出了在内嵌Tomcat环境中获取资源路径的挑战。
摘要由CSDN通过智能技术生成

                                

package training.guojiang.coterie.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.hibernate.loader.entity.NaturalIdEntityJoinWalker;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import training.guojiang.coterie.vo.UploadImage;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("upload")
public class UploadController {

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/image")
    public UploadImage uploadImage(@RequestParam(name = "file")MultipartFile file, HttpServletRequest request) throws IOException {
        //检查文件的大小
        long size = file.getSize();
        if (size>1 * 1024 * 1024){
            throw new RuntimeException("上传失败!上传的文件大小超出了限制!");
        }
        //检查文件的类型
        String contentType = file.getContentType();
        List<String> types = new ArrayList<String>();
        types.add("image/jpeg");
        types.add("image/png");
        types.add("image/gif");
        if (!types.contains(contentType)) {
            throw new RuntimeException("上传失败!不允许上传此类型的文件!");
        }

        //获取原始的文件名:
        String originalFilename = file.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //获取文件的后缀
        String suffix = originalFilename.substring(lastIndexOf - 1);
        String fileName=UUID.randomUUID().toString()+suffix;
        //判断文件夹是否存在:不存在创建
        /**
         * 这里遇到的问题
         * 1:相对路径和绝对路径区别:项目一般都使用相对路径防止项目迁移资源丢失
         *
         *2:resources目录下的资源不会经行编译,需要进行手动编译才能访问到。
         *
         * 3:访问静态资源时访问路径不需要加static: http://localhost:8000/upload/"+fileName
         *
         * 4:由于内嵌tomacat所以 request.getServletContext().getRealPath()
         * 这种方式不能拿到resource的相对路径。
         */
        //String upload1 =ResourceUtils.getURL("classpath:").getPath()+"/static/upload";//这里是获取target/classes/static/upload路径
        String c = System.getProperty("user.dir");//这里是获取项目的相对路径
        String upload1=c+"\\src\\main\\resources\\static\\upload";
        File upload=new File(upload1);
        if(!upload.exists()&&!upload.isDirectory()){
            System.out.println("不存在");
            upload.mkdirs();
            System.out.println("创建成功");
        }


        //保存文件
        File dest=new File(upload,fileName);
        file.transferTo(dest);

        Map<String,String> map=new HashMap();
        map.put("path",fileName);
        map.put("url","http://localhost:8000/upload/"+fileName);
        return UploadImage.builder().status(true).message("上传成功").data(JSONObject.toJSONString(map)).build();
    }

}

这里遇到了很多关于相对路径和绝对路径的获取方法和注意事项

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值