SpringBoot2.X学习之文件上传

本节课讲解SpringBoot的文件上传,使用MultipartFile file,MultipartFile 是File类的子类,源自SpringMVC,我们进入MultipartFile的源码查看他有很多api,等下会具体使用到,下面开始开发:

在static下面新建一个update.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>

 注意:如果上传文件的话表单要加上enctype="multipart/form-data"属性。运行直接访问http://localhost:8080/upload.html

因为页面在static目录下,所以直接访问页面名就行了

下面新建一个返回给前端的结果类:

 

package com.qzsun.springbootdemo.entity;

import java.io.Serializable;

public class JsonData implements Serializable {
	private static final long serialVersionUID = 1L;

	//状态码,0表示成功,-1表示失败
	private int code;
	
	//结果
	private Object data;

	//错误描述
	private String msg;
	
	public int getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public JsonData(int code, Object data) {
		super();
		this.code = code;
		this.data = data;
	}

	public JsonData(int code, String msg,Object data) {
		super();
		this.code = code;
		this.msg = msg;
		this.data = data;
	}
}

 继续写一个controller

package com.qzsun.springbootdemo.controller;

import com.qzsun.springbootdemo.entity.JsonData;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;

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

/**
 * @author sunqizheng
 * @Title: UploadController
 * @ProjectName springbootdemo
 * @Description: TODO
 * @date 2019/1/1813:34
 */
@Controller
public class UploadController {
    private static final String filePath = "D:\\SpringBoot2.0\\SpringBootDemo4\\src\\main\\resources\\static\\images\\";


    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {

        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断

        String name = request.getParameter("name");
        System.out.println("用户名:"+name);

        // 获取文件名
        String fileName = file.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);

        try {
            file.transferTo(dest);

            return new JsonData(0, fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  new JsonData(-1, "fail to save ", null);
    }
}

 MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效),注意:在images目录后面要加上\\,不然会存在目录外面,不在images里面

启动运行并上传图片,发现返回成功

访问图片http://localhost:8080/images/853b8442-0772-410f-bb4b-2a3887ec1efc.jpg

 

如果是上传文件到linux服务器的话需要安装ftp协议,并且使用FTPClient 对象 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用\[1\]和引用\[2\]的内容,Spring Boot 2.0之后的版本可以通过在配置文件中添加以下配置来修改文件上传大小限制: spring.servlet.multipart.max-file-size = 10Mb spring.servlet.multipart.max-request-size = 100Mb 而根据引用\[3\]的内容,如果使用的是Spring Boot 1.5.x版本,可以在application.properties文件中添加以下配置来修改文件上传大小限制: multipart.maxFileSize = 10Mb //单个文件的大小 multipart.maxRequestSize = 100Mb //单次请求的文件的总大小 如果使用的是Spring Boot 1.4版本之后的版本,可以在application.properties文件中添加以下配置来修改文件上传大小限制: spring.http.multipart.maxFileSize = 10Mb spring.http.multipart.maxRequestSize = 100Mb 总结起来,根据不同的Spring Boot版本,可以在配置文件中添加相应的配置来修改文件上传大小限制。 #### 引用[.reference_title] - *1* *2* [Spring boot设置文件上传大小限制](https://blog.csdn.net/weixin_40553655/article/details/88883795)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [springboot上传文件大小限制](https://blog.csdn.net/weixin_42903592/article/details/105047586)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值