springboot实现简单的文件上传功能

springboot实现简单的文件上传功能

pom里面只需要配置一个spring-boot-starter-web就行了

image-20210615162321966

最简易的前端

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h1>文件上传</h1>
<form action="http://localhost:8080/file" method="post" enctype="multipart/form-data">

    文件名称:<input name="fileImage" type="file"/><br>
    <input type="submit" value="提交"/>
</form>
</body>

image-20210615162457746

image-20210615163354112

image-20210615163426678

image-20210615163501857

简单的后端代码:

image-20210615162539902

package com.ws.upload_doc.controller;

/**
 * @author 王顺
 * @date 2021/5/31 - 0:10
 */
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {
    // http://localhost:8080/file
    @RequestMapping("/file")
    public String fileUpload(MultipartFile fileImage) throws IOException {

        System.out.println(fileImage.getOriginalFilename());

        //固定保存在本地的路径:imagePathRoot
        final String imagePathRoot = "F:\\casual2\\";

        //对固定路径进行操作
        File file = new File(imagePathRoot);

        //判断文件夹是否存在,没有就去创建
        if (!file.exists()) {
            file.mkdirs();
        }

        //获得原来的图片名字
        String fileName = fileImage.getOriginalFilename();

        //获取图片的类型jpg or png
        String fileType = fileName.substring(fileName.lastIndexOf("."));

        //创建一个uuid全世界唯一
        String uuid = UUID.randomUUID().toString().replace("-", "");

        //使用原名字+uuid+图片类型构成  保存在本地的文件名字
        String imageFilePath = imagePathRoot + uuid + fileType;

		//将原来的文件保存到新的地址文件夹里去
        fileImage.transferTo(new File(imageFilePath));
        return "upload ok";
    }
}


这里要特地介绍一个新朋友:MultipartFile

  • MultipartFile这个类主要是来实现以表单的形式进行文件上传功能。

  • 常用方法:

    • getOriginalFileName方法获取的是文件的完整名称,包括文件名称+文件拓展名。

    • getContentType方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。

法:

  • getOriginalFileName方法获取的是文件的完整名称,包括文件名称+文件拓展名。

  • getContentType方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。

  • transferTo方法用来将接收文件传输到给定目标路径,会抛出IOException、IllegalStateException异常。该方法在实际项目开发中使用较少。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值