配置准备
在如何配置使用阿里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>