Eclipse搭建springboot项目(三)文件上传

知识点:SpringBoot2.x文件上传:HTML页面文件上传和后端处理

1、springboot文件上传 MultipartFile file,源自SpringMVC
  1)静态页面直接访问:localhost:8080/index.html
    注意点:如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面
  2)MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
    访问路径 http://localhost:8080/images/39020dbb-9253-41b9-8ff9-403309ff3f19.jpeg

2、jar包方式运行web项目的文件上传和访问处理,SpingBoot2.x使用 java -jar运行方式的图片上传和访问处理(核心知识)

  1)文件大小配置,启动类里面配置

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    //单个文件最大
    factory.setMaxFileSize("10240KB"); //KB,MB
    /// 设置总上传数据总大小
    factory.setMaxRequestSize("1024000KB");
    return factory.createMultipartConfig();
}

  2)打包成jar包,需要增加maven依赖

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>     

  如果没加相关依赖,执行maven打包,运行后会报错:no main manifest attribute, in XXX.jar

  GUI:反编译工具,作用就是用于把class文件转换成java文件

  3)文件上传和访问需要指定磁盘路径
  application.properties中增加下面配置
    a) web.images-path=/Users/aaron/Desktop
    b) spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}

  4)文件服务器:fastdfs,阿里云oss,nginx搭建一个简单的文件服务器

一、目录结构

二、文件上传需求

1.前端

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>uploading</title>
<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script src="/js/test.js" type="text/javascript"></script>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/fileController/upload">
        文件:<input type="file" name="head_img" />
        姓名:<input type="text" name="name" />
        <input type="submit" value="上传" />
    </form>
</body>
</html>

2.文件上传Controller

package net.aaron.demo.controller;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.aaron.demo.domain.JsonData;

@Controller
@RequestMapping(value = "fileController")
@PropertySource(value="classpath:application.properties")
public class FileController {
    @Value("${web.filePath}")
    private String filePath;
    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {

         //file.isEmpty(); 判断图片是否为空
         //file.getSize(); 图片大小进行判断

         System.out.println("配置注入打印,文件路径为:"+filePath);

         String name = request.getParameter("name");
         System.out.println("用户名:"+name);

         // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);

        // 获取文件的后缀名,比如图片的jpeg,png
        // lastIndexOf 是从右向左查某个指定的字符串在字符串中最后一次出现的位置
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);

        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:"+fileName);

        File dest = new File(filePath + fileName);

            try {
                file.transferTo(dest);
                 return new JsonData(0, fileName);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return  new JsonData(-1, "fail to save ", null);
    }

}

3.返回JsonData类

package net.aaron.demo.domain;

import java.io.Serializable;

public class JsonData implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    //状态码,0表示成功,-1表示失败
    private int code;

    //结果
    private Object data;

    //错误描述
    private String msg;

    public JsonData(int code, Object data) {
        super();
        this.code = code;
        this.data = data;
    }

    public JsonData(int code, String msg,Object data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

}

4.访问:

原文地址:https://www.cnblogs.com/aaronRhythm/p/10957409.html

时间: 2024-08-29 06:22:58

Eclipse搭建springboot项目(三)文件上传的相关文章

Springboot如何启用文件上传功能

网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文件上传功能: 其实你啥都不用做,直接用就是了.文件上传相关的随着你的webStarter引入,就被引入到你的项目里面了. POM依赖: 代码: 注意事项: springboot文件上传 单个请求包含的文件默认大小:1MB-10MB 请求格式POST 参数格式form-data 如果出错了,请仔细查看报错信息!

springboot框架,文件上传问题===org.springframework.web.HttpMediaTypeNotSupportedException: Content type &#39;multipart/form-data;

使用IDEA开发springboot项目,需求中要提交数据项和文件上传,同时接收实体bean对象和文件,后台Controller接收配置方式: Controller代码如下: 1 @RequestMapping(value="/comment",method = RequestMethod.POST) 2 public @ResponseBody RetResult saveIndustryComment(HttpServletRequest request,@RequestParam

JavaWeb项目实现文件上传动态显示进度

很久没有更新博客了,这段时间实在的忙的不可开交,项目马上就要上线了,要修补的东西太多了.当我在学习JavaWeb文件上传的时候,我就一直有一个疑问,网站上那些博客的图片是怎么上传的,因为当提交了表单之后网页就跳转了.后来我学习到了Ajax,我知道了浏览器可以异步的发送响应,这时我又有新的疑问,那就是在我上传一些文件的时候,那些网站的上传进度是怎么做到的,因为servlet直到上传完成之后才完成响应. 最近我们的项目中有一个地方中需要用到一个功能,当用户点击一个处理按钮时,前台会实时的显示后台处理

SpringBoot: 6.文件上传(转)

1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="uploadFile" method="post" enct

springboot+vue实现文件上传

https://blog.csdn.net/mqingo/article/details/84869841 技术: 后端:springboot 前端框架:vue 数据库:mysql pom.xml: <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</versi

jQuery插件之路(三)——文件上传(支持拖拽上传)

好了,这次咱一改往日的作风,就不多说废话了,哈哈.先贴上源代码地址,点击获取.然后直接进入主题啦,当然,如果你觉得我有哪里写的不对或者欠妥的地方,欢迎留言指出.在附上一些代码之前,我们还是先来了解下,上传文件的时候需要利用的一些必要的知识. 首先我们要说的就是FileReader对象,这是一个HTML5提出的,专门用来异步的读取用户计算机上文件的对象,这里有详细的介绍.所以如果我们想要使用它,那么首先我们得先创建一个FileReader对象. var fr = new FileReader()

Web项目中文件上传Filter处理

最近遇到一个文件上传的项目,而且在这个项目中遇到的文件上传的次数还是挺多的,所以就写了个Filter过滤器.这一个想法还是从一本书上看到的,所以原则上说并不是在下原创.不过因为补充了一点东西,所以,嘿嘿,不说了. 首先需要写个Filter: package yin.filter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream

Minio 整合springboot 开发 实现文件上传

Minio 作为对象存储,灵活方便,结合java 实现minio 文件上传 1.搭建maven环境,添加依赖包 <properties> <minio.version>4.0.0</minio.version></properties> <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <versio

springboot实现多文件上传

一说明 spingMVC支持文件上传,我们通过Apach 的 commons-fileupload 包的CommonsMultipartResolver 去实现了 spingMVC的MultipartResolver . 本文章的示例是个简单的多文件上传,根据不同的业务自行修改. 二pom.xlm <dependencies> <dependency> <groupId>commons-fileupload</groupId> <artifactId&