Springboot文件上传

文件上传

package com.property.controller.upload;

import com.alibaba.fastjson.JSON;
import com.property.entity.Journalism;
import com.property.service.JournalismService;

import com.property.utile.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.struts2.ServletActionContext;
import org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/upload")
public class FileUpload {

    @Autowired
    private JournalismService journalismService;


    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpSession session;

    /***
     *  解决前端跨域请求 [注解]
     *  @CrossOrigin(origins = "*",maxAge = 8378)
     * */


    //当前日期 重新格式化日期  输出格式: 2014-05-05
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String dtTime = df.format(date);

    @Value("${imgpath}")
    String imgpath;


    /**
     * 添加  1.执行文件上传  2.获取文件上传后路径赋值  3.数据入库
     * @author sourceyang
     * @date 2021/03/16
     * */
    @CrossOrigin(origins = "*",maxAge = 8378)
    @RequestMapping(value = "/uploadimg",method = RequestMethod.POST)
    @ResponseBody
    public Map uploadimg(@RequestParam(value = "fileName") MultipartFile file) {

        String result_msg="";//上传结果信息
        Map<String,Object> root=new HashMap<String, Object>();

        if (file.getSize() / 1000 > 100){
            result_msg="图片大小不能超过100KB";
        }else{
            //判断上传文件格式
            String fileType = file.getContentType();
            if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
                String fileName = file.getOriginalFilename();

                //获取文件后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));

                //获取文件名称 (不带后缀)
                String Name = "";
                if ((fileName != null) && (fileName.length() > 0)) {
                    int dot = fileName.lastIndexOf('.');
                    if ((dot > -1) && (dot < (fileName.length()))) {
                        Name = fileName.substring(0, dot);
                    }
                }

                //重新生成文件名
                String paths =  Name + RandomUtils.nextInt(0,1000000) + "_" + dtTime  + suffixName;

                String lujing = "image/";
                //重新拼接
                String loca = lujing + paths;

                //存入到session中
                session = request.getSession();
                session.setAttribute("loca",loca);
                request.getSession().setMaxInactiveInterval(120*60);

                if (FileUtils.upload(file, imgpath, paths)) {

                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
                    String relativePath="img/"+fileName;
                    root.put("relativePath",relativePath);//前端根据是否存在该字段来判断上传是否成功
                    result_msg="图片上传成功";
                }
                else{
                    result_msg="图片上传失败";
                }
            }
            else{
                result_msg="图片格式不正确,请选择png或jpg格式文件";
            }
        }

        root.put("result_msg",result_msg);

        String root_json=JSON.toJSONString(root);
        System.out.println(root_json);
        return  root;
    }



    /**
     * [新增]
     * @author sourceyang
     * @date 2021/03/09
     **/
    @CrossOrigin(origins = "*",maxAge = 8378)
    @RequestMapping("/insert")
    @ResponseBody
    public String insert(Journalism journalism){
         String loca =  (String) session.getAttribute("loca");

        journalism.setJournalismimg(loca);
        journalism.setJournalismdate(dtTime);
        return journalismService.insert(journalism);
    }

    /**
     * [新增]
     * @author sourceyang
     * @date 2021/03/17
     **/
    @CrossOrigin(origins = "*",maxAge = 8378)
    @RequestMapping("/update")
    public String update(Journalism journalism){
        String loca =  (String) session.getAttribute("loca");

        journalism.setJournalismimg(loca);
        journalism.setJournalismdate(dtTime);
        return journalismService.update(journalism);
    }

}

文件上传工具类

package com.property.utile;

import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

//文件上传
public class FileUtils {


    /**
     * @param file     文件
     * @param path     文件存放路径
     * @param fileName 保存的文件名
     * @return
     * @date 2021/03/16
     * @author sourceyang
     */
    public static boolean upload(MultipartFile file, String path, String fileName) {

        //确定上传的文件名
        String realPath = path + "/" + fileName;

        System.out.println("上传文件:" + realPath);

        File dest = new File(realPath);


        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}

yml定义上传路劲

#启动端口
server:
  port: 8378
#配置数据源连接
spring:
  datasource:
    username: ****
    password: ****
    url: jdbc:mysql://localhost:3306/#####?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
  devtools:  #开启热加载
    restart:
      enabled: true
imgpath: D:/fileUpload/ #自定义文件上传路径

#映射地址
mybatis:
  mapper-locations : classpath:mapper/*.xml

资源映射

package com.property.utile;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Value("${imgpath}")
    String imgpath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

         /**
          * 映射静态资源绝对路径
          * addResourceHandler : 访问映射路径
          * addResourceLocations 资源绝对路径
          * */
        registry.addResourceHandler("/image/**").addResourceLocations("file:"+imgpath);
    }

}

最近在优快云翻阅了好多文章,大部分收费积分形式,作者在这里吐槽一下。真的很烦
下一篇是前端bootstrop前端文件上传及回显图片。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值