spring项目实现上传文件

文件上传并非将文件上传至服务器,实际上是在服务器 创建 了一个文件,并用原文件的内容来填充新文件,从而实现上传

在服务器中需要有专门的目录来存放 上传路径 ,在新的上传请求传来时,必应判断该上传路径是否存在,若 不存在 ,则需要先 创建 该上传目录。

在服务器中的文件,为了防止上传文件的名称重复,从而产生冲突等问题,应用 UUID 来生成随机 ID 为新文件命名

文件上传应当将上传至服务器的 url 地址保存在数据库中

获取原文件名称

在前端向后端发起上传请求时,传参中必然带有文件信息,此时在 Controller 层对应的接口中会接收到 MultipartFile 类型的 file

通过以下代码可获取原文件的名称:

String OriginFileName = file.getOriginalFilename();

将远程文件存入本地
假设,存放新文件的变量名称为 newFile ,远程文件变量名称为 oldFile

则可通过以下代码将远程文件保存至本地文件中:

oldFile.transferTo(newFile);

文件 Entity 层代码详解
在 Controller 中可以将该实体转换为 Json 格式字符串进行返回

@Data
public class LocalFileJson {
	private String filename;
	private String url;
	private String originalName;
	private String type; // 即文件后缀
	private long size;
	private String status;
	private String message;
}

Controller 层代码详解

@RestController
@RequestMapping("/utils")
public class commonUtils {
@PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) throws JsonProcessingException {
        /* 判断文件是否为空 */
        if(!file.isEmpty()) {
            /* 文件上传根路径 */
            String uploadPath = "F:\\";  // require custom
            File uploadDir = new File(uploadPath);
            /* 若上传目录不存在,则先创建目录 */
            if(!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            /* 获取原文件名称 */
            String originalFilename = file.getOriginalFilename();
            /* 获取文件大小 */
            long fileSize = file.getSize(); // byte
            /* 获取 URL 前缀 */
            StringBuffer tmpUrl = request.getRequestURL();
            String tmpUri = request.getRequestURI();
            String urlPrefix = String.valueOf(tmpUrl.substring(0, tmpUrl.length() - tmpUri.length()));
            /* 获取文件后缀 */
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            /* 使用 UUID 生成随机新名称 */
            String fileName = UUID.randomUUID().toString() + suffixName;
            File newFile = new File(uploadPath + "/" + fileName);
            try {
                /* 远程文件保存本地 */
                file.transferTo(newFile);
                ObjectMapper objectMapper = new ObjectMapper();
                LocalFileJson localFileJson = new LocalFileJson();
                localFileJson.setSize(fileSize);
                localFileJson.setOriginalName(originalFilename);
                localFileJson.setFilename(fileName);
                localFileJson.setUrl(urlPrefix + "/" + fileName); // require custom
                localFileJson.setType(suffixName);
                localFileJson.setStatus("SUCCESS");
                localFileJson.setMessage(originalFilename + " Upload Successfully !");
                String res = objectMapper.writeValueAsString(localFileJson); // 将对象转换为 Json 格式进行返回
                return res;
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Upload File ERROR !");
                ObjectMapper objectMapper = new ObjectMapper();
                LocalFileJson localFileJson = new LocalFileJson();
                localFileJson.setStatus("FAILED");
                localFileJson.setMessage(originalFilename + " Upload Failed !");
                String res = objectMapper.writeValueAsString(localFileJson);
                return res;
            }
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            LocalFileJson localFileJson = new LocalFileJson();
            localFileJson.setStatus("FAILED");
            localFileJson.setMessage("Cannot Empty !");
            String res = objectMapper.writeValueAsString(localFileJson);
            return res;
        }
    }
}

axios 请求

this.axios({
	method: "POST",
	url: "/utils/upload",
	data:'' // 此处应为上传的文件
}).then((res) => {
	console.log(res);
}).catch((error) => {
	console.lo(error);
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值