SpringMVC中实现将文件上传到阿里云OSS服务器

配置准备

在如何配置使用阿里OSS服务器时

官方文档给了很详细的配置说明

可以根据官方文档进行配置,本文具体实现如何实现文件传入OSS

https://yq.aliyun.com/articles/702854?spm=a2c4e.11155472.0.0.56c0753bH0NDxN

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="#" id="uploadForm" enctype="multipart/form-data">
        用户名: <input type="text" name="userName"><br>
        头像:<input type="file" name="userPic"><br>
         <input type="button" id="uploadBtn" value="提交"><br>
    </form>

</body>
<script  src="lib/jquery-1.9.1.min.js"></script>
<script>
    $("#uploadBtn").click(function () {
        /**
         * $("#uploadForm") 是一个JQuery对象
         * $("#uploadForm")[0] 将JQuery对象转成DOM元素
         * @type {FormData}
         */
        var formData = new FormData($("#uploadForm")[0])
        $.ajax({
            url:"/file/fileUploadByAli.action",
            type:"POST",
            data:formData,
            async:false,
            cache:false,
            contentType:false,
            processData:false,
            success:function (result) {
                console.log(result);
            },
            error:function (error) {
                console.log("error:"+error);
            }
        })
    })
</script>
</html>

后端代码:

package com.hxy.controller;

import com.aliyun.oss.OSSClient;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
public class FileUpLoadController {

    @RequestMapping(value = "/file/fileUploadByAli.action")
    public String fileUploadByAli(HttpServletResponse response, HttpServletRequest request){
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 使用刚刚创建的accessKeyId和accessKeySecret
        String accessKeyId = "********";
        String accessKeySecret = "******";
        String bucketName = "****";

        //文件上传相关的类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload( factory );
        //设置文件编码
        upload.setHeaderEncoding( "UTF-8" );
        //文件列表
        List fileList = null;
        try {
            //获取文件
            fileList = upload.parseRequest( request );
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator<FileItem> iterator = fileList.iterator();
        while (iterator.hasNext()){
            FileItem item = iterator.next();
            // 判断某项是否是普通的表单类型
            if(!item.isFormField()){
                //字段名称
                String fieldName = item.getFieldName(); //文件对应字段名称,就是input中name的值
                //文件 XXX.doc
                String fileName = item.getName();
                //获取文件后缀名
                String suffix = fileName.substring( fileName.lastIndexOf( '.' ) ); //.doc
                //获取时间戳,防止文件重复
                long id = new Date().getTime();
                //获取保存路径
                String savePath = request.getServletContext().getRealPath( "img" );
                //设置文件路径
                String fileUrl = String.format( "%s/%d%s",savePath,id,suffix);
                File file = new File( fileUrl );
                try {
                    //将文件上传到目标文件夹
                    item.write( file );
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //阿里OSS文件类
                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                //上传到OSS的那个模块下,哪个文件夹,哪个文件
                ossClient.putObject(bucketName, fileUrl, file);
                // 设置URL过期时间为1小时。
                Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
                // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                URL url = ossClient.generatePresignedUrl(bucketName, fileUrl, expiration);
                ossClient.shutdown();
                System.out.println(url.toString());
            }else {
                String fieldName = item.getFieldName();
                String value = item.getString();
                System.out.println(fieldName +"->"+value);
            }
        }
        return null;
    }
}

POM.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.first.springmvc</groupId>
    <artifactId>firsts-pringmvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>4.12</junit.version>
        <spring.version>4.3.10.RELEASE</spring.version>
        <mybatis.version>3.4.4</mybatis.version>
        <mybatis.spring.version>1.3.1</mybatis.spring.version>
        <c3p0.version>0.9.5.2</c3p0.version>
        <jstl.version>1.2</jstl.version>
        <log4j.version>1.2.17</log4j.version>
        <fastjson.version>1.2.35</fastjson.version>
        <slf4j.version>1.7.25</slf4j.version>
        <jackson.version>2.9.4</jackson.version>
        <commons-fileupload.version>1.3.3</commons-fileupload.version>
        <commons-io.version>2.5</commons-io.version>
        <commons-codec.version>1.10</commons-codec.version>
        <aspectjweaver.version>1.8.10</aspectjweaver.version>
        <mysql.version>5.1.34</mysql.version>
    </properties>

    <dependencies>
        <!--阿里云oss依赖-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>

        <!-- Junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- spring包 core、web、oxm、tx、jdbc、webmvc、aop、context、test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

        <!-- 导入Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- 导入c3p0的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <!-- 日志文件管理包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>


        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- json和bean之间相互转换 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- 上传组件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>${commons-codec.version}</version>
        </dependency>


        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectjweaver.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0-b07</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>



</project>

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring MVC,可以使用MultipartResolver来处理文件上传。MultipartResolver是一个接口,Spring提供了两个实现类:CommonsMultipartResolver和StandardServletMultipartResolver。前者是通过Jakarta Commons FileUpload实现的,后者是通过Servlet 3.0的API实现的。这里以CommonsMultipartResolver为例介绍文件上传。 1. 在Spring配置文件添加multipartResolver配置: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置上传文件的最大值--> <property name="maxUploadSize" value="5242880"/> </bean> ``` 2. 在Controller编写上传文件的处理方法: ``` @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { //获取文件名 String fileName = file.getOriginalFilename(); //获取文件的字节数组 byte[] bytes = file.getBytes(); //将字节数组写入到文件 String filePath = "/path/to/save/file/" + fileName; File outputFile = new File(filePath); OutputStream outputStream = new FileOutputStream(outputFile); outputStream.write(bytes); outputStream.close(); //将上传文件的信息保存到数据库 //... return "redirect:/success"; } catch (IOException e) { e.printStackTrace(); } } return "redirect:/error"; } ``` 在上面的方法,@RequestParam("file")用于获取上传的文件,MultipartFile是Spring封装的文件上传对象,其包含了上传文件的相关信息,例如文件名、大小、内容等。通过调用getOriginalFilename()方法可以获取文件名,通过调用getBytes()方法可以获取文件的字节数组。接着,将字节数组写入到文件,最后将上传文件的相关信息保存到数据库。 3. 将上传的文件存储到文件服务器上 如果需要将上传的文件存储到文件服务器上,可以使用FTPClient或SFTPClient等工具实现。具体实现方法可以参考FTPClient或SFTPClient的使用文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无名一小卒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值