当前位置: 代码网 > it编程>编程语言>Java > 如何基于SpringWeb MultipartFile实现文件上传、下载功能

如何基于SpringWeb MultipartFile实现文件上传、下载功能

2024年07月20日 Java 我要评论
前言在web开发中,文件上传是一个常见的功能需求。spring框架提供了multipartfile接口,用于处理文件上传请求。multipartfile可以代表一个多部分文件上传请求中的一个文件,提供

前言

在web开发中,文件上传是一个常见的功能需求。spring框架提供了multipartfile接口,用于处理文件上传请求。multipartfile可以代表一个多部分文件上传请求中的一个文件,提供了一系列方法用于获取文件的各种属性和内容,使得在后端处理文件上传变得十分方便。下面我们将介绍multipartfile在web应用中的几种常见使用场景。

1. 图片上传

在web应用中,图片上传是一种常见的场景。用户需要上传头像、相片、证件照等图片文件,而后端需要接收并保存这些文件。使用multipartfile接口可以轻松地实现图片文件的接收和处理。通过获取文件的原始文件名、内容类型、大小等属性,我们可以实现对图片文件的有效管理和存储。例如,我们可以将图片文件保存到服务器的文件系统中,或者将其存储到云存储服务中。

2. 文件下载

除了文件上传,文件下载也是web应用中常见的功能需求。使用multipartfile接口,我们可以实现文件的下载功能。在服务器端,我们可以将文件作为multipartfile对象进行处理,并通过设置响应头信息,将文件作为下载内容返回给客户端。客户端接收到文件后,可以将其保存到本地磁盘或进行其他处理。

3. 文件编辑

在web应用中,有时候用户需要对上传的文件进行编辑操作,例如修改文件名、修改文件内容等。使用multipartfile接口,我们可以实现对文件的编辑功能。首先,我们可以通过multipartfile接口获取上传的文件对象,然后对其进行相应的编辑操作。例如,我们可以修改文件的名称、修改文件的内容等。编辑完成后,我们可以将修改后的文件保存到服务器或返回给客户端。

4. 文件预览和展示

在web应用中,有时候我们需要将上传的文件进行预览或展示。例如,在文档管理系统中,用户需要预览或下载文档文件。使用multipartfile接口,我们可以实现文件的预览和展示功能。我们可以将文件作为multipartfile对象进行处理,然后将其内容转换为适当的格式进行展示。例如,对于pdf文件,我们可以使用pdf阅读器插件进行展示;对于图片文件,我们可以将其直接展示在网页上。

5. 文件批量上传和处理

在实际应用中,有时候用户需要批量上传多个文件,并对这些文件进行处理。使用multipartfile接口,我们可以实现文件的批量上传和处理功能。我们可以将多个文件作为一个多部分文件上传请求进行处理,然后对每个文件进行相应的操作。例如,我们可以将多个图片文件批量上传到服务器,并对它们进行压缩、裁剪等处理。

代码

package com.javagpt.back.controller;

import com.javagpt.application.context.userappcontextholder;
import com.javagpt.application.file.fileapplicationservice;
import com.javagpt.application.file.filedto;
import com.javagpt.common.annotation.respsuccess;
import com.javagpt.common.constant.emconstant;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import jakarta.servlet.http.httpservletrequest;
import jakarta.servlet.http.httpservletresponse;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;

import java.io.ioexception;

@api(tags = "文件接口")
@slf4j
@restcontroller
@requestmapping(emconstant.api_v1 + "/file")
@respsuccess
@requiredargsconstructor
public class filecontroller {

    private final fileapplicationservice fileapplicationservice;

    @apioperation("通用文件上传")
    @postmapping(value = "/uploadfile")
    public filedto uploadfile(@requestparam("file") multipartfile multipartfile) throws ioexception {
        long enterpriseid = userappcontextholder.getcurrentuser().getenterpriseid();
        filedto filedto = fileapplicationservice.savefile(enterpriseid, multipartfile);
        return filedto;
    }

    //@preauthorize("hasauthority('mp:file:download')")
    @apioperation("下载文件")
    @getmapping(value = "/downloadfile")
    public void download(@requestparam(value = "id") long id, httpservletresponse response) throws ioexception {
        fileapplicationservice.downloadfile(response, id, userappcontextholder.getcurrentuser().getenterpriseid());
    }

    @apioperation("查看文件信息")
    @getmapping(value = "/info")
    public filedto fileinfo(@requestparam(value = "id") long id) throws ioexception {
        return fileapplicationservice.findbyid(id);
    }

    @apioperation("下载视频")
    @getmapping(value = "/downloadfile2")
    public void download2(@requestparam(value = "id") long id, httpservletrequest request, httpservletresponse response) throws ioexception {
        fileapplicationservice.downloadvideo(request, response, id, userappcontextholder.getcurrentuser().getenterpriseid());
    }
}
package com.javagpt.application.file;

import com.javagpt.common.exception.businessruntimeexception;
import com.javagpt.common.oos.ossservice;
import com.javagpt.common.util.modelutils;
import com.javagpt.common.util.springresponseutils;
import com.javagpt.file.entity.fileentity;
import com.javagpt.file.repository.filerepository;
import jakarta.servlet.http.httpservletrequest;
import jakarta.servlet.http.httpservletresponse;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.io.filenameutils;
import org.apache.commons.io.ioutils;
import org.apache.commons.lang3.stringutils;
import org.springframework.http.httpheaders;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import org.springframework.web.multipart.multipartfile;

import java.io.*;

@service
@slf4j
@requiredargsconstructor
public class fileapplicationservice {

    private final ossservice ossservice;

    private final filerepository filerepository;


    public filedto findbyid(long id) {
        fileentity fileentity = filerepository.findbyid(id);
        return modelutils.convert(fileentity, filedto.class);
    }

    @transactional
    public filedto savefile(long enterpriseid, multipartfile file) {
        fileentity fileentity = savefile(enterpriseid, file, null);
        return modelutils.convert(fileentity, filedto.class);
    }

    @transactional
    public fileentity savefile(long enterpriseid, multipartfile file, string filename) {
        string originalfilename = file.getoriginalfilename();
        string name = stringutils.isblank(filename) ? filenameutils.getbasename(originalfilename) : filename;
        string suffix = filenameutils.getextension(originalfilename);
        long size = file.getsize();
        fileentity fileentity = new fileentity();
        fileentity.setname(name).setsuffix(suffix).setsize(size).setenterpriseid(enterpriseid);
        fileentity = fileentity.save();
        string key = fileentity.getpath();
        inputstream inputstream = null;
        try {
            inputstream = file.getinputstream();
        } catch (ioexception e) {
            log.error("savefile error:", e);
            throw businessruntimeexception.error("上传文件失败");
        }
        ossservice.uploadfile(inputstream, key);
        ioutils.closequietly(inputstream);
        return fileentity;
    }


    @transactional
    public fileentity savefile(file file) {
        long size = file.length();
        fileentity fileentity = new fileentity();
        string basename = filenameutils.getbasename(file.getname());
        string extension = filenameutils.getextension(file.getname());
        fileentity.setname(basename).setsuffix(extension).setsize(size);
        fileentity = fileentity.save();
        string key = fileentity.getpath();
        fileinputstream inputstream = null;
        try {
            inputstream = new fileinputstream(file);
            ossservice.uploadfile(inputstream, key);
        } catch (filenotfoundexception e) {
            log.error("savefile error:", e);
            throw businessruntimeexception.error("上传文件失败");
        }
        ioutils.closequietly(inputstream);
        return fileentity;
    }


    public void downloadfile(httpservletresponse response, long fileid, long enterpriseid) throws ioexception {
        fileentity fileentity = filerepository.findbyid(fileid);
        if (fileentity == null) {
            throw businessruntimeexception.error("无效的文件id");
        }
        string key = fileentity.getpath();
        inputstream inputstream = ossservice.downloadfile(key);
        springresponseutils.writeandflushresponse(inputstream, response, fileentity.filefullname());
    }


    public void downloadvideo(httpservletrequest request, httpservletresponse response, long fileid, long enterpriseid) throws ioexception {

        fileentity fileentity = filerepository.findbyid(fileid);
        if (fileentity == null) {
            throw businessruntimeexception.error("无效的文件id");
        }
        response.setheader(httpheaders.accept_ranges, "bytes");
        long filesize = fileentity.getsize();
        long start = 0, end = filesize - 1;
        //判断前端需不需要分片下载
        if (stringutils.isnotblank(request.getheader("range"))) {
            response.setstatus(httpservletresponse.sc_partial_content);
            string numrange = request.getheader("range").replaceall("bytes=", "");
            string[] strrange = numrange.split("-");
            if (strrange.length == 2) {
                start = long.parselong(strrange[0].trim());
                end = long.parselong(strrange[1].trim());
                //若结束字节超出文件大小 取文件大小
                if (end > filesize - 1) {
                    end = filesize - 1;
                }
            } else {
                //若只给一个长度  开始位置一直到结束
                start = long.parselong(numrange.replaceall("-", "").trim());
            }
        }
        long rangelength = end - start + 1;
        string contentrange = new stringbuffer("bytes ").append(start).append("-").append(end).append("/").append(filesize).tostring();
        response.setheader(httpheaders.content_range, contentrange);
        response.setheader(httpheaders.content_length, string.valueof(rangelength));
        string key = fileentity.getpath();
        inputstream inputstream = ossservice.downloadfile2(key, start, end);
        springresponseutils.writeandflushresponse(inputstream, response, fileentity.filefullname());
    }
}

总之,multipartfile接口在web应用中具有广泛的应用场景,可以实现文件上传、下载、编辑、预览和批量处理等功能。通过熟练掌握multipartfile接口的使用方法和技巧,我们可以更加高效地处理文件上传和下载请求,提升web应用的用户体验和功能性能。

总结

到此这篇关于如何基于springweb multipartfile实现文件上传、下载功能的文章就介绍到这了,更多相关springweb multipartfile文件上传下载内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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