文件上传/下载

文件上传(最简单版本):

以图片为例:

前端逻辑:

前端我给大家粘贴到这里了(最简单的代码,视频未实现)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/addAppendix" method="post"
      class="form-horizontal" id="saveForm"
      enctype="multipart/form-data">
    <div class="form-group row">
        <label  class="control-label col-md-2">图片上传</label>
        <div class="col-md-10">
            <input class="form-group" name="photo" type="file" />
        </div>
    </div>
    <div class="form-group row">
        <label  class="control-label col-md-2">视频上传</label>
        <div class="col-md-10">
            <input class="form-group" name="media" type="file" />
        </div>
    </div>
    <button type="submit">提交</button>
</form>
</body>
</html>

简单的上传页面,可以直接copy(在此声明,重点是后端的接受文件后的处理逻辑)。

后端逻辑:

1.首先,通过参数接受文件

public AjaxResult addAppendix(@RequestParam("photo") MultipartFile file) 

接受文件需要用MultipartFile类型,还有需要注意,此次测试中的@RequestParam中的photo一定要和前端相同(因为我测试时候直接copy别人的,所以报错了,注意!!!)

2.通过file.getOriginalFilename()获取文件名

可以看到只是图片的全称(包括:图片名 + "." + 后缀) 。

3.获取文件的后缀名:

        在此提供两种方法:

                1.通过substring

 String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);

                2.引入common.io的依赖,调用getExtension()

String suffixName = FilenameUtils.getExtension(fileName);

结果如下:

4.取新的文件名

        这个完全是看自己,最常见的是利用uuid或者是data时间之类等不易重复的。 

5.设置上传路径

        最简单的方式是直接写在字符串中。(这里的路径是需要注意转义的)

//注意使用转义字符,java的代码开发中\是代表转义字符的,/才是代表路径符号
String path = "D:\\";  
or
String path1 = "D:/";

            还有一种是通过写在配置文件的方式。(说明:这种方式是很便利,因为配置文件是可以应用在每个方法的,十分推荐!!!

# 定义文件上传路径 D:\\ 此为路径,可根据自己需求修改
file.fileUploadPath:
  D:\
@Component
@ConfigurationProperties(prefix = "file")
@PropertySource(value = "application.yml")
public class FileUploadProp {

    private String fileUploadPath;

    public  String getFileUploadPath() {
        return fileUploadPath;
    }

    public void setFileUploadPath(String fileUploadPath) {
        this.fileUploadPath = fileUploadPath;
    }

}
 @Autowired
    private FileUploadProp fileUploadProp;

三步即可完成,直接在controller里面使用

6.根据路径判断有没有文件夹,没有则新建(这里面的dir就是我们上传的路径)
 File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
7.拼接文件新名称
 String transFerName = newFileName+"."+suffixName;
        //创建file对象,新地址新名字
        File newFile = new File(realPath, transFerName);
8.上传文件
file.transferTo(newFile);

以上就是最简单的文件上传的步骤。具体的代码我放在最后:

UploadController:

package org.example.controller;

import org.apache.commons.io.FilenameUtils;
import org.example.entity.AjaxResult;
import org.example.entity.FileUploadProp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
public class UploadController {
    @Autowired
    private FileUploadProp fileUploadProp;

    // 文件上传保存
    @PostMapping(value = "/addAppendix", produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult addAppendix(@RequestParam("photo") MultipartFile file) {

     
        //文件名
        String fileName = file.getOriginalFilename();
        //文件后缀名
        String suffixName = FilenameUtils.getExtension(fileName);
//        String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
        //新文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        //拿到路径
        String realPath = fileUploadProp.getFileUploadPath();
        //注意使用转义字符,java的代码开发中\是代表转义字符的,/才是代表路径符号
        //String path = "D:\\";
       // String path1 = "D:/";
        //文件夹不存在的时候创建一个
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
//        String extension = FilenameUtils.getExtension(fileName);
        String transFerName = newFileName+"."+suffixName;
        //创建file对象,新地址新名字
        File newFile = new File(realPath, transFerName);

        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }

        return AjaxResult.success("成功上传");
    }

}

读取文件的entity:

package org.example.entity;



import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "file")
@PropertySource(value = "application.yml")
public class FileUploadProp {

    private String fileUploadPath;

    public  String getFileUploadPath() {
        return fileUploadPath;
    }

    public void setFileUploadPath(String fileUploadPath) {
        this.fileUploadPath = fileUploadPath;
    }

}

消息类(copy ruoyi):

package org.example.entity;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Objects;


/**
 * 操作消息提醒
 *
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object>
{
    private static final long serialVersionUID = 1L;

    /** 状态码 */
    public static final String CODE_TAG = "code";

    /** 返回内容 */
    public static final String MSG_TAG = "msg";

    /** 数据对象 */
    public static final String DATA_TAG = "data";

    /**
     * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
     */
    public AjaxResult()
    {
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     *
     * @param code 状态码
     * @param msg 返回内容
     */
    public AjaxResult(int code, String msg)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     *
     * @param code 状态码
     * @param msg 返回内容
     * @param data 数据对象
     */
    public AjaxResult(int code, String msg, Object data)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (!StringUtils.isEmpty(data))
        {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     *
     * @return 成功消息
     */
    public static AjaxResult success()
    {
        return AjaxResult.success("操作成功");
    }

    /**
     * 返回成功数据
     *
     * @return 成功消息
     */
    public static AjaxResult success(Object data)
    {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @return 成功消息
     */
    public static AjaxResult success(String msg)
    {
        return AjaxResult.success(msg, null);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static AjaxResult success(String msg, Object data)
    {
        return new AjaxResult(200, msg, data);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult warn(String msg)
    {
        return AjaxResult.warn(msg, null);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult warn(String msg, Object data)
    {
        return new AjaxResult(201, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @return 错误消息
     */
    public static AjaxResult error()
    {
        return AjaxResult.error("操作失败");
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @return 错误消息
     */
    public static AjaxResult error(String msg)
    {
        return AjaxResult.error(msg, null);
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 错误消息
     */
    public static AjaxResult error(String msg, Object data)
    {
        return new AjaxResult(404, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @param code 状态码
     * @param msg 返回内容
     * @return 错误消息
     */
    public static AjaxResult error(int code, String msg)
    {
        return new AjaxResult(code, msg, null);
    }

    /**
     * 是否为成功消息
     *
     * @return 结果
     */
    public boolean isSuccess()
    {
        return Objects.equals(200, this.get(CODE_TAG));
    }

    /**
     * 是否为警告消息
     *
     * @return 结果
     */
    public boolean isWarn()
    {
        return Objects.equals(201, this.get(CODE_TAG));
    }

    /**
     * 是否为错误消息
     *
     * @return 结果
     */
    public boolean isError()
    {
        return Objects.equals(404, this.get(CODE_TAG));
    }

    /**
     * 方便链式调用
     *
     * @param key 键
     * @param value 值
     * @return 数据对象
     */
    @Override
    public AjaxResult put(String key, Object value)
    {
        super.put(key, value);
        return this;
    }
}

 之后还会持续更新文件(包括图片、视频、ppt、excel等等文件),还有一些注意事项:比如文件的大小,文件的路径位置(绝对路径、相互路径)等等。

此文章针对小白,大佬请指点!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值