Spring boot的上传文件


spring boot 工程已经打包添加了multipart.MultipartFile; 依赖,

配置文件上传的文件大小以及位置

(小白一个,请指教)

application.yml 的配置

spring
	servlet:
	    multipart:
	      max-file-size: 20MB
	      max-request-size: 20MB
	      location: D://image #(你的路径可不填)

上传的方法

在component 添加上传的方法 可以调用上传的方法。不用每个Controller都写。

package com.example.springbook.componet;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Component
public class Compoent {

    /**
     * 上传文件的名称
     */
    public static String filename;

    public static Integer current=1;

    public static int number=0;


    /**
     * 上传方法
     *
     * @param image
     * @param request
     */
    public static void uploadFile(MultipartFile image, HttpServletRequest request) {
        if (!image.isEmpty()) {
            //上传相应的位置
            String path = request.getServletContext().getRealPath("/resources/static/image");
            System.out.println("上传我位置:" + path);
            File file = new File(path);
            //判处路径是否存在
            if (!file.exists()) {
                file.mkdirs();
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            filename = df.format(new Date()) + image.getOriginalFilename();
            System.out.println(filename);

            // 将上传文件保存到相应位置
            try {
                image.transferTo(new File(path + File.separator + filename));
//                image.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * //每天凌晨四点执行
     * 返回随机页数
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public static void currentPage(int cu){
        number++;
        System.out.println(number);
        if (cu/15>1){
            current=new Random().nextInt((cu/15)+1)+1;
            System.out.println(current);
        }
    }

}

注意

如果application 没用配置文件,springboot 上传的路径可能会上传到临时文件夹(报错)。这时你可以创建webapp或static文件夹在项目的根目录,可以达到上传到项目文件里。

上传的Html 的from 表单 需要添加 enctype=“multipart/form-data” 。

在这里插入图片描述

调用上传方法

例如: 在Controlller 的简单的上传

@RequestMapping(value = "/upload.do",method = RequestMethod.POST)
    public String upload(HttpServletRequest request, User user,
                         @RequestParam("file")MultipartFile file) {
        if (!file.isEmpty()){
            Compoent.uploadFile(file,request);
           
            String imageurl="/static/image/"+Compoent.filename;;
            System.out.println(imageurl);

            return "listImage";
//            return "success";
        }else {
            return "error";
        }

    }

上传项目图片的地址到数据库

/**
     * 用户图片修改
     * @param userId
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/userImage.do")
    public String userImage(Integer userId, MultipartFile file, HttpServletRequest request) {
        if (file!=null){
            Compoent.uploadFile(file,request);
            //图片地址
            String imageurl = localhost + ":" + port + "/static/image/" + Compoent.filename;
            boolean aBoolean=userService.updateImageByUserId(userId,imageurl);
            if (aBoolean){
                return  "图片修改成功,Success!"
            }
        }
        return "修改失败,非法输入,输入的值为空,error!";
    }

如果出现上传到临时文件 ;路径:“C:\Users\admin\AppData\Local\Temp\tomcat.1760054768116885118.1105” 时;
可以配置 working directory
在这里插入图片描述

文件的复制

//
MultipartFile mf;
//目录文件
File file = new File(ctxPath + File.separator + bizPath + File.separator );
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
//文件的复制(具有上传的类似功能,具体还不清楚)
FileCopyUtils.copy(mf.getBytes(), savefile);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值