SpringBoot中关于图片的上传入门

1.前端准备

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YvFU2lZI-1599828035567)(/img/bVbOFyv)]

<%@ page language="java" contentType="text/html; charset=UTF-8"  
 pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
</head>  
<body>  
   <h1>实现文件长传</h1>  
   <!--enctype="开启多媒体标签" -->  
   <form action="http://localhost:8091/filetest" method="post"  
 enctype="multipart/form-data">  
      <input name="fileImage" type="file" />  
      <input type="submit" value="提交"/>  
   </form>  
</body>  
</html>

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TBj7Xtzd-1599828035573)(/img/bVbOFy7)]

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){}
 <form action="http://localhost:8091/filetest" method="post"  
 enctype="multipart/form-data">  
      <input name="fileImage" type="file" />  
      <input type="submit" value="提交"/>  
   </form>  
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();  
        } 

猜你喜欢

转载自blog.csdn.net/weixin_43388956/article/details/108541400