一、创建Maven项目
参考:SpringBoot第 1 讲:HelloWorld_秦毅翔的专栏-CSDN博客
二、修改pom.xm
<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>
<!-- SpringBoot支持01、parent:Begin -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<!-- SpringBoot支持01、parent:End -->
<groupId>org.personal.qin.demos</groupId>
<artifactId>upload_demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- java版本 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SpringBoot:Begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot:End -->
<!-- SpringMVC:Begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- SpringMVC:End -->
<!-- 文件上传:Begin -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 文件上传:End -->
<!--跨服务器上传:Begin -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<!--跨服务器上传:End -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- 资源文件拷贝插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- SpringBoot支持03、添加SpringBoot的插件支持:Begin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- SpringBoot支持03、添加SpringBoot的插件支持:End -->
</plugins>
</build>
</project>
三、本站文件上传
package demo.upload.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import demo.upload.entity.FileInfo;
/**
* 本站文件上传
*/
@RestController
@RequestMapping("/file")
public class TestFileController {
private String folder = "/Volumes/Elements_Mac/WorkSpace/spring_boot/upload_demo";
@PostMapping
public FileInfo upload(MultipartFile file) throws Exception {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
File localFile = new File(folder, new Date().getTime()+".txt");
// file.getInputStream(); //读取文件的输入流,之后就可以写到其他的文件服务器了
file.transferTo(localFile); //将上传的文件内容写入到本地指定的文件中
return new FileInfo(localFile.getAbsolutePath(), localFile.getPath());
}
@GetMapping("/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
try( //jdk7以后的语法,执行之后,jdk会自动关流,无需提供finally手动关流
InputStream inputStream = new FileInputStream(folder+"/"+id+".txt");
OutputStream outputStream = response.getOutputStream();
){
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=test.txt");
//将文件的输入流复制到输出流中(将文件的内容写到response中)
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、跨域文件上传
4.1、Jesy跨域文件上传工具类
package demo.upload.utils;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import demo.upload.entity.FileInfo;
/**
* 跨服务器文件上传工具类
*
* @author qin
*
*/
public class JesyFileUploadUtil {
/**
* 上传文件
*
* @param request --从request对象中获取上传的文件
* @param fileName --文件名
* @param servlerUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
* @return
* @throws IOException
*/
public static FileInfo uploadFile(HttpServletRequest request, String fileName, String serverUrl) throws IOException {
//把request请求转换成多媒体的请求对象
MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
//根据文件名获取文件对象
MultipartFile cm = mh.getFile(fileName);
//获取文件的上传流
byte[] fbytes = cm.getBytes();
//重新设置文件名
String newFileName = "";
newFileName += new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上
//随机生成一个3位的随机数
Random r = new Random();
for(int i=0; i<3; i++) {
newFileName += r.nextInt(10); //生成一个0-10之间的随机整数
}
//获取文件的扩展名
String orginalFilename = cm.getOriginalFilename();
String suffix = orginalFilename.substring(orginalFilename.indexOf("."));
//创建jesy服务器,进行跨服务器上传
Client client = Client.create();
//把文件关联到远程服务器
//http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
WebResource resource = client.resource(serverUrl+"/upload/"+newFileName+suffix);
//上传
resource.put(String.class, fbytes);
//图片上传成功后要做的事儿
//1、ajax回调函数做图片回显(需要图片的完整路径)
//2、将图片的路径保存到数据库(需要图片的相对路径)
String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
String relativePath = "/upload/"+newFileName+suffix; //相对路径
// //生成一个json响应给客户端
// String resultJson = "{\"fullPath\":\""+fullPath+"\", \"relativePath\":\""+relativePath+"\"}";
// return resultJson;
return new FileInfo(fullPath, relativePath);
}
}
4.2、RestController
package demo.upload.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import demo.upload.entity.FileInfo;
import demo.upload.utils.JesyFileUploadUtil;
/**
* 跨域文件上传
*/
@RestController
@RequestMapping("jersey")
public class TestJerseyUploadController {
private final String PIC_URL = "http://127.0.0.1:8080/ssm_image_server";
@PostMapping(value="uploadPic")
@ResponseBody
public FileInfo uploadPic(HttpServletRequest reqeust, String fileName) {
//调用跨服务器上传文件的工具类方法上传文件
FileInfo result = null;
try {
result = JesyFileUploadUtil.uploadFile(reqeust, fileName, PIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
五、BootApplication启动类
package demo.upload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UploadBootApplication {
public static void main(String[] args) {
SpringApplication.run(UploadBootApplication.class, args);
}
}
七、模拟文件服务器并且配置
7.1、创建一个web项目,并且修改Tomcat服务器模拟文件服务器
创建一个项目,图片服务器项目,图片服务器和上传图片的项目端口不一致。
7.2、修改文件服务器上传权限
7.3、允许跨域请求
在web.xml中找到下面这行代码,并在其下方添加如下代码段:
<!-- The mapping for the HTTP header security Filter -->
<!-- The mapping for the HTTP header security Filter -->
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
七、源代码
https://download.csdn.net/download/qzc70919700/30503692