当前位置: 代码网 > it编程>编程语言>Java > java文件/图片的上传与下载以及MultipartFile详解

java文件/图片的上传与下载以及MultipartFile详解

2025年02月14日 Java 我要评论
一、概述multipartfile为org.springframework.web.mutipart包下的一个类,也就是说如果想使用multipartfile这个类就必须引入spring框架,换句话说

一、概述

multipartfile为org.springframework.web.mutipart包下的一个类,也就是说如果想使用multipartfile这个类就必须引入spring框架,换句话说,如果想在项目中使用multipartfile这个类,那么项目必须要使用spring框架才可以,否则无法引入这个类。

multipartfile翻译成中文来讲就是“多组件的文档”,不用太在乎他的中文含义,一般来讲使用multipartfile这个类主要是来实现以表单的形式进行文件上传功能。

二、multipartfile中的方法

getname方法

getname方法获取的是前后端约定的传入文件的参数的名称

getoriginalfilename方法

getoriginalfilename方法获取的是文件的完整名称,包括文件名称+文件拓展名。

getcontenttype方法

getcontenttype方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。

isempty方法

isempty方法用来判断传入的文件是否为空,如果为空则表示没有传入任何文件。

getsize方法

getsize方法用来获取文件的大小,单位是字节。

getbytes方法

getbytes方法用来将文件转换成一种字节数组的方式进行传输,会抛出ioexception异常。

getinputstream方法

getinputstream方法用来将文件转换成输入流的形式来传输文件,会抛出ioexception异常。

transferto方法

transferto方法用来将接收文件传输到给定目标路径

三、multipartfile的一些使用技巧

  • (1)我们在使用multipartfile作为参数传递的时候,可以将multipartfile声明为一个数组,这样就能支持多文件传输,如果只需要传输一个文件,则去掉数组就好了。
  • (2)可以根据multipartfile的getsize方法来获取到传输文件的大小,这样就能限定传输过来的文件的大小了。

四、上传代码显示

  • 业务逻辑代码:
package cn.xcy.demo.controller;

import cn.hutool.core.io.fileutil;
import cn.xcy.demo.flieutils;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;

import javax.servlet.servletoutputstream;
import javax.servlet.http.httpservletresponse;
import java.io.file;
import java.io.ioexception;

@slf4j
@restcontroller
@requestmapping("/file")
public class fileuploadcontroller {
    /**
     *  上传文件
     *  1、判断文件是否为空
     *  2、获取文件名、文件类型、文件大小(可以限定文件类型、以及文件大小)
     *  3、设置文件上传路径
     *  4、以流的方式将文件输出
     *  5、返回上传成功
     * @param file
     * @return
     * @throws exception
     */
    @postmapping("/upload")
    public string uploadimage(@requestparam("file") multipartfile file) throws exception{
        // 判断文件是否为空
        if (file.isempty()) {
            return "上传失败";
        }
        //文件类型为
        string contenttype = file.getcontenttype();
        log.info("文件类型为:" + contenttype);
        if (contenttype.equals("image/jpeg")){
            return "请上传正确格式的文件";
        }
        // 获取原始文件名
        string filename = file.getoriginalfilename();
        log.info("上传的文件名为:" + filename);
        try {
            // 将文件保存到指定位置
            byte[] bytes = file.getbytes();
            log.info("文件大小为:" + bytes.length);
            // todo: 根据业务需求选择合适的存储方式,比如保存到本地磁盘或云存储
//            获取生成后的文件名
            string s = flieutils.generaterandomfilename(filename);
//            将文件保存到指定位置
            flieutils.upload(file,"c:\\users\\liguoming\\desktop",s);
            return "上传成功";
        } catch (exception e) {
            e.printstacktrace();
            return "上传失败";
        }
    }

}
  • flieutils工具类:
package cn.xcy.demo;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.multipart.multipartfile;
import java.io.file;
import java.util.uuid;

@slf4j
public class flieutils {
    /**
     * @param file     文件
     * @param filename 新的随机文件名
     */
    public static void upload(multipartfile file, string destpath, string filename) {
        file dest = new file(destpath + file.separator + filename);
        //判断文件父目录是否存在
        if (!dest.getparentfile().exists()) {
            dest.getparentfile().mkdirs();
        }
        try {
            //保存文件
            file.transferto(dest);
        } catch (exception e) {
            log.info("save file exception. {}", e.getmessage());
        }

    }

    /**
     * 输出文件的后缀名
     * @param filename
     * @return
     */
    public static string getsuffix(string filename) {
//        filename.substring(filename.lastindexof("."))
//        是c#中的字符串操作,它的作用是从文件名字符串中截取最后一个点(.)及其后面的所有字符。这个操作可以用来获取文件的扩展名。
        return filename.substring(filename.lastindexof("."));
    }

    /**
     * 输出文件的新名称 (名字+后缀名)
     * @param filename
     * @return
     */
    public static string generaterandomfilename(string filename) {
        return uuid.randomuuid() + getsuffix(filename);
    }

    /**
     * @param name
     * @description 设置响应头部信息
     * @throws
     * @return java.lang.string
     * @date 2023-08-02 13:39:15
     * @author lgm
     */
    public static string filecontenttype(string name) {
        string result = "";
        string filetype = name.tolowercase();
        if (filetype.endswith(".png")) {
            result = "image/png";
        } else if (filetype.endswith(".gif")) {
            result = "image/gif";
        } else if (filetype.endswith(".jpg") || filetype.endswith(".jpeg")) {
            result = "image/jpeg";
        } else if (filetype.endswith(".svg")) {
            result = "image/svg+xml";
        } else if (filetype.endswith(".doc")) {
            result = "application/msword";
        } else if (filetype.endswith(".xls")) {
            result = "application/x-excel";
        } else if (filetype.endswith(".zip")) {
            result = "application/zip";
        } else if (filetype.endswith(".pdf")) {
            result = "application/pdf";
        } else if (filetype.endswith(".mpeg")) { //mp3
            result = "audio/mpeg";
        } else if (filetype.endswith(".mp4")) {
            result = "video/mp4";
        } else if (filetype.endswith(".plain")) {
            result = "text/plain";
        } else if (filetype.endswith(".html")) {
            result = "text/html";
        } else if (filetype.endswith(".json")) {
            result = "application/json";
        } else{
            result = "application/octet-stream";
        }
        return result;
    }
}

五、下载的代码显示

  • 业务逻辑代码:
/**
     *  下载文件
     *  1、需要传入文件名称
     *  2、先将文件的存放路径+名称获取到
     *  3、设置响应头,告诉浏览器需要下载文件夹
     *  4、设置响应体,将文件读取出来,写入到响应体中
     *  5、response.getoutputstream()  输出字节流, 客户端会下载字节流并生成文件保存本地
     * @param filename
     * @param response
     * @return
     * @throws ioexception
     */
    @requestmapping("/fileload")
    public string fileload(@requestparam("filename")string filename, httpservletresponse response) throws ioexception {
        // 文件的存放位置
        string filepath = "c:\\users\\liguoming\\desktop\\" + filename;
        file file = new file(filepath);
        // 设置响应头,告诉浏览器要下载文件
        // response.setcontenttype()是设置响应类型的 浏览器读取的是什么文件 依据文件类型,告诉浏览器接下来要做的是什么
        // application/octet-stream  告诉浏览器需要下载二进制流数据(如常见的文件下载)
        response.setcontenttype("application/octet-stream");
        /**
         * response.setheader("content-disposition", "attachment; filename=" +new string( filename.getbytes("gb2312"), "iso8859-1" ));
         * 在确保附件文件名都是简体中文字的情况下,那么这个办法确实是最有效的,不用让客户逐个的升级ie。
         * 如果台湾同胞用,把gb2312改成big5就行。但现在的系统通常都加入了 国际化的支持,普遍使用utf-8。
         * 如果文件名中又有简体中文字,又有繁体中文,还有日文。那么乱码便产生了。另外,在上firefox (v1.0-en)下载也是乱码。
         */
        response.setheader("content-disposition", "attachment; filename=" +new string( filename.getbytes("gb2312"), "iso8859-1" ));
        //response.getoutputstream()  输出字节流, 客户端会下载字节流并生成文件保存本地
        servletoutputstream outputstream = response.getoutputstream();
        outputstream.write(fileutil.readbytes(file));
        outputstream.close();
        return "success";
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com