no15-第十一章第二次课-springmvc的单文件和多文件上传-rest风格

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: ssm 专栏: ssm框架课 标签: 文件上传 rest风格

2023-01-03 11:48:36 772浏览

文件上传和rest风格

rest风格写法

前端:

 <a href="${pageContext.request.contextPath}/detail/2">rest测试</a>

后端control

@Controller
public class TestRestController {

    /*查询*/
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id){
        System.out.println(id);

        return "rest_details";
    }

springMVC的文件上传

1.单文件上传

  • 先引入两个jar

commons-fileupload

commons-io

  • 编写页面代码

  <form method="post" action="uploadImg" enctype="multipart/form-data">
    <input type="file" name="img">
    <input type="submit" value="上传">
  </form>

  <p>${message}</p>
  • 编写control代码
 @RequestMapping("/uploadImg")
    public String uploadImg(MultipartFile img, HttpServletRequest request){

        Boolean flag =true;
        if(!img.isEmpty()){//判断前端有没有传文件
            //1.文件打算上传到哪里呢?哪个路径下呢

            /* request.getServletContext()  相当于application  */
            String realPath = request.getServletContext().getRealPath("/upimgs/user");
            //2.创建目录
            File file = new File(realPath);
            if(!file.exists()){
                file.mkdirs();
            }
            //3.拿到用户上传的文件的原始名字----进一步拿到文件的后缀名
            String originalFilename = img.getOriginalFilename();//原始名字 xx.xxxyyy.yyyxx.JPG  PNG
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));



            //4.判断文件的大小——超过1m的文件不允许上传
            if(img.getSize()>1024000){
                //不跳转成功页面
                flag=false;
                request.setAttribute("error","文件超过1m不允许上传");

            }else if(fileSuffix.equalsIgnoreCase(".jpg")
                    || fileSuffix.equalsIgnoreCase(".png")
                    ||fileSuffix.equalsIgnoreCase(".jpeg")
                    ||fileSuffix.equalsIgnoreCase(".gif")
            ){//再判断一下文件的格式
                //开始上传到服务器

                //文件重命名
                String newFileName= UUID.randomUUID()+fileSuffix;
                File saveFile = new File(realPath+"/"+newFileName);
                try {
                    img.transferTo(saveFile);
                } catch (IOException e) {
                    flag=false;
                    request.setAttribute("error","文件上传失败");
                    e.printStackTrace();
                }

            }else{
                flag=false;
                request.setAttribute("error","文件格式不对,必须上传图片才行");
            }
        }else{
            flag=false;
            request.setAttribute("error","文件必填");
        }


        if(flag ){
            return "uploadSuccess";//跳到上传成功的页面
        }else{
            return "rest";//跳到rest
        }
    }
  • 编写的springmvc的配置文件
  <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--        设置文件上传的默认编码格式-->
        <property name="defaultEncoding" value="utf-8"></property>
        <!--        显示文件上传的大小,单位字节-->
        <property name="maxUploadSize" value="1024000"></property>
    </bean>

2.多文件上传

@RequestMapping("/uploadImgMore")
    public String uploadImgMore(MultipartFile[] lifeImg, HttpServletRequest request){
        Boolean flag =true;
        //1.文件打算上传到哪里呢?哪个路径下呢

        /* request.getServletContext()  相当于application  */
        String realPath = request.getServletContext().getRealPath("/upimgs/user/life");
        //2.创建目录
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        //3.拿到用户上传的文件的原始名字----进一步拿到文件的后缀名
        for (MultipartFile img : lifeImg) {
            if(!img.isEmpty()){
                String originalFilename = img.getOriginalFilename();//原始名字 xx.xxxyyy.yyyxx.JPG  PNG
                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                //4.判断文件的大小——超过1m的文件不允许上传
                if(img.getSize()>1024000){
                    //不跳转成功页面
                    flag=false;
                    request.setAttribute("error","文件超过1m不允许上传");

                }else if(fileSuffix.equalsIgnoreCase(".jpg")
                        || fileSuffix.equalsIgnoreCase(".png")
                        ||fileSuffix.equalsIgnoreCase(".jpeg")
                        ||fileSuffix.equalsIgnoreCase(".gif")
                ){//再判断一下文件的格式
                    //开始上传到服务器
                    File saveFile = new File(realPath+"/"+originalFilename);
                    try {
                        img.transferTo(saveFile);
                    } catch (IOException e) {
                        flag=false;
                        request.setAttribute("error","文件上传失败");
                        e.printStackTrace();
                    }

                }else{
                    flag=false;
                    request.setAttribute("error","文件格式不对,必须上传图片才行");
                }
            }else{
                flag=false;
                request.setAttribute("error","多个都必须上传");
            }

        }


        if(flag ){
            return "uploadSuccess";//跳到上传成功的页面
        }else{
            return "rest";//跳到rest
        }
    }
}
  <form method="post" action="uploadImgMore" enctype="multipart/form-data">
    <input type="file" name="lifeImg"><br/>
    <input type="file" name="lifeImg"><br/>
    <input type="file" name="lifeImg"><br/>
    <input type="submit" value="上传">
  </form>

补充:

1.前端只上传图片的话可以:accept="image/*"

文档介绍:html - input - accept 上传文件类型

文章地址:https://www.cnblogs.com/zc-lee/p/16086688.html

文件类型

accept属性值

类型

*.3gpp

audio/3gpp, video/3gpp

3GPP Audio/Video

*.ac3

audio/ac3

AC3 Audio

*.asf

allpication/vnd.ms-asf

Advanced Streaming Format

*.au

audio/basic

AU Audio

*.css

text/css

Cascading Style Sheets

*.csv

text/csv

Comma Separated Values

*.doc

application/msword

MS Word Document

*.dot

application/msword

MS Word Template

*.dtd

application/xml-dtd

Document Type Definition

*.dwg

image/vnd.dwg

AutoCAD Drawing Database

*.dxf

image/vnd.dxf

AutoCAD Drawing Interchange Format

*.gif

image/gif

Graphic Interchange Format

*.htm

text/html

HyperText Markup Language

*.html

text/html

HyperText Markup Language

*.jp2

image/jp2

JPEG-2000

*.jpe

image/jpeg

JPEG

*.jpeg

image/jpeg

JPEG

*.jpg

image/jpeg

JPEG

*.js

text/javascript, application/javascript

JavaScript

*.json

application/json

JavaScript Object Notation

*.mp2

audio/mpeg, video/mpeg

MPEG Audio/Video Stream, Layer II

*.mp3

audio/mpeg

MPEG Audio Stream, Layer III

*.mp4

audio/mp4, video/mp4

MPEG-4 Audio/Video

*.mpeg

video/mpeg

MPEG Video Stream, Layer II

*.mpg

video/mpeg

MPEG Video Stream, Layer II

*.mpp

application/vnd.ms-project

MS Project Project

*.ogg

application/ogg, audio/ogg

Ogg Vorbis

*.pdf

application/pdf

Portable Document Format

*.png

image/png

Portable Network Graphics

*.pot

application/vnd.ms-powerpoint

MS PowerPoint Template

*.pps

application/vnd.ms-powerpoint

MS PowerPoint Slideshow

*.ppt

application/vnd.ms-powerpoint

MS PowerPoint Presentation

*.rtf

application/rtf, text/rtf

Rich Text Format

*.svf

image/vnd.svf

Simple Vector Format

*.tif

image/tiff

Tagged Image Format File

*.tiff

image/tiff

Tagged Image Format File

*.txt

text/plain

Plain Text

*.wdb

application/vnd.ms-works

MS Works Database

*.wps

application/vnd.ms-works

Works Text Document

*.xhtml

application/xhtml+xml

Extensible HyperText Markup Language

*.xlc

application/vnd.ms-excel

MS Excel Chart

*.xlm

application/vnd.ms-excel

MS Excel Macro

*.xls

application/vnd.ms-excel

MS Excel Spreadsheet

*.xlt

application/vnd.ms-excel

MS Excel Template

*.xlw

application/vnd.ms-excel

MS Excel Workspace

*.xml

text/xml, application/xml

Extensible Markup Language

*.zip

application/zip
application/x-zip-compressed

Compressed Archive

2.多文件同时选中上传

加属性multiple="multiple"

好博客就要一起分享哦!分享海报

此处可发布评论

评论(1展开评论

蓝色妖姬 能力:10

2023-01-06 13:26:50

老师厉害
点击查看更多评论

展开评论

您可能感兴趣的博客

客服QQ 1913284695