在webapps\Root文件夹下创建用于接收上传文件的upload文件夹
readonly false
commons-fileupload commons-fileupload 1.3.1 javax.servlet javax.servlet-api 3.1.0 com.sun.jersey jersey-client 1.19 com.sun.jersey jersey-core 1.19
server:port: 8070
spring:servlet:multipart:#设置单个文件的大小,-1表示不限制,单位MBmax-file-size: 10MB#设置单次请求的文件总大小,-1表示不限制,单位MBmax-request-size: 100MB
package demo.util;import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.Random;/*** 跨服务器文件上传工具类** @author qin**/
public class JesyFileUploadUtil {/*** 上传文件** @param file --文件名* @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server* @return* @throws IOException*/public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {//重新设置文件名String newFileName = new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上//随机生成一个3位的随机数Random r = new Random();for(int i=0; i<3; i++) {newFileName += r.nextInt(10); //生成一个0-10之间的随机整数}//获取文件的扩展名String orginalFilename = file.getOriginalFilename();String suffix = orginalFilename.substring(orginalFilename.indexOf("."));//创建jesy服务器,进行跨服务器上传Client client = Client.create();//把文件关联到远程服务器//例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpgWebResource resource = client.resource(serverUrl+"/"+newFileName+suffix);//上传//获取文件的上传流resource.put(String.class, file.getBytes());//图片上传成功后要做的事儿//1、ajax回调函数做图片回显(需要图片的完整路径)//2、将图片的路径保存到数据库(需要图片的相对路径)
// String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径String relativePath = "/upload/"+newFileName+suffix; //相对路径return relativePath;}
}
@RequestMapping("/uploadFile")@CrossOrigin(origins = "*")public String upload(MultipartFile fileName){String url = "http://localhost:8080/upload";String path = "";try {path = JesyFileUploadUtil.uploadFile(fileName, url);} catch (IOException e) {e.printStackTrace();}return path;}
Title