栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot如何上传图片

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot如何上传图片

1.前端准备

<%@ page language="java" contentType="text/html; charset=UTF-8" 
 pageEncoding="UTF-8"%> 
 
 
 
 
Insert title here 
 
 
  实现文件长传 
   
   
 

2.实现文件上传的步骤说明

package com.jt.controller; 
 
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; 
 
@RestController 
public class FileTestController { 
@RequestMapping("/filetest") 
 public String file(MultipartFile fileImage){ 
    
 String fileDir = "F:/CloudMusic/images"; 
 File file = new File(fileDir);
 if(!file.exists()){ 
 file.mkdirs(); 
 } 
 
    
 String fileName = fileImage.getOriginalFilename(); 
 File imageFile = new File(fileDir+"/"+fileName); 
  
 try { 
      fileImage.transferTo(imageFile);//Transfer the received file to the given destination file. 
 }catch(IOException e){ 
      e.printStackTrace(); 
    } 
      return "ok"; 
 
  } 
}

3.代码解释

3.1 前提

MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。

public String file(MultipartFile fileImage){}

3.2 封装文件的上传路径

封装文件上传的路径,如果文件存在直接封装,如果文件不存在使用 file.mkdirs() 方法创建多级目录

String fileDir = "F:/CloudMusic/images"; 
 File file = new File(fileDir);
 if(!file.exists()){ 
 file.mkdirs(); 
 }

3.3 封装文件的名称

fileImage.getOriginalFilename()//Return the original filename in the client's filesystem. 返回客户端文件系统中的原始文件名。

String fileName = fileImage.getOriginalFilename(); 
 File imageFile = new File(fileDir+"/"+fileName);

3.4 文件的上传

fileImage.getOriginalFilename()//Transfer the received file to the given destination file. 将接收到的文件传输到给定的目标文件。

try { 
      fileImage.transferTo(imageFile);//Transfer the received file to the given destination file. 
 }catch(IOException e){ 
      e.printStackTrace(); 
    }

以上就是SpringBoot如何上传图片的详细内容,更多关于SpringBoot 上传图片的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/131858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号