SpringBoot第 6 讲:SpringBoot+jersey跨域文件上传

一、创建Maven项目

参考:SpringBoot第 1 讲:HelloWorld_秦毅翔的专栏-CSDN博客

SpringBoot第 6 讲:SpringBoot+jersey跨域文件上传_第1张图片 

二、修改pom.xm 


	4.0.0
	
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.2.RELEASE
	
	

	org.personal.qin.demos
	upload_demo
	1.0.0-SNAPSHOT
	jar

	
		UTF-8
		UTF-8
		
		1.8
	

	
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		

		
		
			org.springframework
			spring-webmvc
		
		
		
		
		
			commons-fileupload
			commons-fileupload
			1.3.1
		
		
		
		
			com.sun.jersey
			jersey-client
			1.19
		
		
			com.sun.jersey
			jersey-core
			1.19
		
		

	

	
		${project.artifactId}
		
			
			
				org.apache.maven.plugins
				maven-resources-plugin
				
					UTF-8
				
			
			
			
				org.apache.maven.plugins
				maven-compiler-plugin
				
					1.8
					1.8
					UTF-8
				
			
			
			
				org.springframework.boot
				spring-boot-maven-plugin
			
			
		
	

三、本站文件上传

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);
	}
}

六、源代码

https://download.csdn.net/download/qzc70919700/30503692

你可能感兴趣的:(SpringBoot+,spring,boot,maven,spring)