前后端文件交互

  1. 上传

  1. 前端:form表单要求如下:1.必须采用post的请求方式 2.必须使用file属性的input 3.表单的enctype属性必须是multipart

  1. 后端:如果服务中可能接收到文件流,那么直接在Controller具体服务函数形参中接收一个MultiPartFile对象即可

  1. 但是!!!!MultiPartFile对象的名字必须和html标签中name的属性要一致,否则找不到

  1. 下载

作为附件下载或者直接在浏览器中打开

package com.mtj.controller;

import com.mtj.generally.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.FileInputStream;
import java.util.Arrays;
import java.util.UUID;

/**
 * 处理文件的上传和下载
 */
@RestController
@RequestMapping(value = "/common")
@Slf4j
public class CommonController {
    private String basePath = new String("c:\\intel\\");

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/upload")
    private Result upload(MultipartFile file, HttpServletRequest request) {
        log.info("File upload is Loading..." + file.toString());

        //使用UUID随机生成文件名防止重复
        String fileName = UUID.randomUUID().toString();

        //动态的获取文件的后缀名,注意这个正则中的.得用\\.来表示
        String[] split = file.getOriginalFilename().split("\\.");

        String LastName = split[split.length - 1];

        String finalName = fileName + "." + LastName;

        log.info("finalName:" + finalName);

        try {
            file.transferTo(new File(basePath + finalName));
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return new Result(1, finalName, "上传成功");
    }

    /**
     * 文件下载
     * @param response
     * @param name
     */
    @GetMapping(value = "/download")
    private void download(HttpServletResponse response, String name) {
        try {
            //从本地获取对应图片
            FileInputStream fin = new FileInputStream(basePath + name);

            //获取写入response中
            ServletOutputStream fou = response.getOutputStream();
            fou.write(fin.readAllBytes());

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值