springboot文件上传 MultipartFile file

1、讲解springboot文件上传 MultipartFile file,源自SpringMVC        
                注意点:
                  如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面
         MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)

直接上html代码

<!DOCTYPE html>
<html>
  <head>
    <title>uploadimg.html</title>

    <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script src="/js/test.js" type="text/javascript"></script>

  </head>

  <body>
     <form enctype="multipart/form-data" method="post" action="/upload">
       文件:<input type="file" name="head_img"/>
       姓名:<input type="text" name="name"/>
       <input type="submit" value="上传"/>
      </form>
   
  </body>
</html>

 

下面是controller代码,只是demo,实际开发逻辑代码写在server实现层

package com.study.studyBoot.controller;

import com.study.studyBoot.model.JsonData;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
public class FileController {
    //final Logger logger = logger.getLogger(FileController.class);

    private static final String filePath = "D:/IDEA/studyBoot/src/main/resources/static/images/";

    /**
     * @Description: 上传图片接口
     * @author: panboyang
     * @date :2019-06-26 17:55:17
     * @params: head_img表单提交名称 ,filePath路径自定义
     */
    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img") MultipartFile multipartFile, HttpServletRequest request) {
        //multipartFile.getSize();  根据自己的个人情况来定义限制上传大少
        JsonData data = new JsonData();
        if (multipartFile.isEmpty()) {
            return new JsonData(-1, "文件不能为空");
        } else {//获取用户名
            String name = request.getParameter("name");
            System.out.println("用户名:" + name);
            // 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            System.out.println("上传的文件名为:" + fileName);
            // 获取文件的后缀名,比如图片的jpeg,png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为:" + suffixName);
            // 文件上传后的路径
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("转换后的名称:" + fileName);
            File dest = new File(filePath + fileName);
           //dest.getPath() 返回文件路径
            try {
                multipartFile.transferTo(dest);
                return  new JsonData(1,dest.getPath(),"sues to save");
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return  new JsonData(-1,null,"fail to save");
        }


    }

}
在Java Spring Boot中,可以使用MultipartFile类型来实现文件上传功能。可以通过创建一个Controller,并使用@RequestPart注解和MultipartFile类来接收文件。以下是一个简单的文件上传的例子: ```java @Controller @RequestMapping("/upload") public class UploadController { @PostMapping("/") @ResponseBody public String uploadFile(@RequestPart("file") MultipartFile file) { // 处理文件上传逻辑 if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); // 将文件保存到指定位置 try { file.transferTo(new File("path/to/save/" + fileName)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); return "文件上传失败"; } } else { return "文件为空"; } } } ``` 在上述例子中,我们在Controller中创建了一个接收文件上传的方法`uploadFile`,使用@RequestPart注解来接收MultipartFile类型的文件。然后,我们可以通过调用`transferTo`方法将文件保存到指定位置。 请注意,上述例子中只涉及单个文件上传。如果需要上传多个文件,在方法参数中使用MultipartFile数组即可。同时,还可以对文件进行更多的处理和验证操作,例如限制文件大小、验证文件类型等。 这就是Java Spring Boot中实现上传MultipartFile类型的简单例子。你可以根据自己的需求对代码进行修改和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springBoot使用MultipartFile实现多文件 上传](https://blog.youkuaiyun.com/m0_67393039/article/details/125243766)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [java springboot实现上传MultipartFile类型 进行HttpRequest调用传入第三方上传接口](https://blog.youkuaiyun.com/A_yonga/article/details/125894648)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习没有捷径,如果有那便是持之以恒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值