序言:

  该案例是采用springMvc实现跨服务器图片上传功能,其中用到的主要类和工具有:CommonsMultipartResolver、jquery.form.js。如果要实现多个文件上传,只需要在input元素中加入multiple="multiple",即可选择多个文件进行上传。另外本文的上传的文件路径不是在tomcat下对应的文件夹中,而是在workspace对应的文件夹中存在。该案例使用ajax上传页面不刷新,多个图片可立即回显,并将其相对路径可以随着表单一起保存到数据库中,而文件则存放在文件服务器中。还有,点击选择,选择了文件之后,文件是依附于form表单,因此在使用jquery.form.js的$("#formId").ajaxSubmit(options)提交的表单,提交之后,文件是以流的形式通过HttpServeltRequest传递到Controller当中,之后再通过向下强转成HttpServeltRequest的实现接口MultipartHttpServletRequest进一步获取到文件集合。

代码:

springMvc-servlet.xml文件中需要配置:

  

<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20180000"></property>
</bean>

jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.form.js"></script> <script type="text/javascript">
function fileOnchage(){
var option = {
type:"post",
data:{myUploadFile:'uploadFile'},
dataType:"string",
url:"${pageContext.request.contextPath }/uploadController/upload.do",
success:function(data){
//String格式json,转json对象
var json = $.parseJSON(data);
//将对象转String格式的json(例如数组)
//JSON.stringify('obj');
for(var i in json){
$("#picImg").append('<img id="myImg" src="'+json[i].fullPath+'"/>');
}
}
}
$("#fileForm").ajaxSubmit(option);
}
</script>
</head>
<body>
<form id="fileForm" method="post">
<div id="picImg"></div>
<input type="file" name="uploadFile" value="请选择" multiple="multiple" onchange="fileOnchage()"/>
<input type="hidden" id="relativePath" value="">
</form>
</body>
</html>

controller:

package com.cissst.it;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource; @Controller
@RequestMapping("/uploadController")
public class UploadController { @InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
binder.registerCustomEditor(CommonsMultipartFile.class,
new ByteArrayMultipartFileEditor());
} @RequestMapping("upload")
@ResponseBody
public String upload(String myUploadFile,HttpServletRequest request){ //多部件请求对象
MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
//获取文件list集合
List<MultipartFile> files = mh.getFiles(myUploadFile);
//创建jersey服务器,进行跨服务器上传
Client client = Client.create();
//json格式的图片路径
List<String> listJsonPath = new ArrayList<String>();
for (MultipartFile file : files) {
String newFileName="";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
newFileName = sdf.format(new Date());
Random r = new Random();
//{'':''}
String jsonPath="";
for(int i =0 ;i<3;i++){
newFileName=newFileName+r.nextInt(10);
}
//原始的文件名
String originalFilename = file.getOriginalFilename();
//截取文件扩展名
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//绝对路径(另一台服务器文件路径)
String fullPath="http://127.0.0.1:8083/springMvc_fileServler/upload/"+newFileName+suffix;
//相对路径(数据库中存放的文件名)
String relativePath=newFileName+suffix;
//各自的流
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
//将文件传入文件服务器
WebResource resource = client.resource(fullPath);
resource.put(String.class, inputStream);
jsonPath = "{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}";
listJsonPath.add(jsonPath);
}
JSONArray jsonArray = JSONArray.fromObject(listJsonPath);
return jsonArray.toString();
} }

服务器信息:

  master server's and point :

  

  

  file server's and point:

  

  you must confrim two server's point diffrence

上传后的文件:

  

页面回显:

  

springMvc---跨服务器文件上传(实测总结)的更多相关文章

  1. 前后端分离跨服务器文件上传-Java SpringMVC版

    近来工作上不上特别忙,加上对后台java了解一点,所以就抽时间,写了一个java版本的前后端分离的跨服务器文件上传功能,包括前后端代码. 一.Tomcat服务器部分 1.Tomcat服务器 单独复制一 ...

  2. django 12天(跨域,文件上传,下载,cookie,session)

    django 12天(跨域,文件上传,下载) 跨域 什么是跨域 1.协议不同 2.端口不同 3.主机不同 如何解决跨域 1.安装django-cors-headers模块 2.在settings.py ...

  3. (转)SpringMVC学习(九)——SpringMVC中实现文件上传

    http://blog.csdn.net/yerenyuan_pku/article/details/72511975 这一篇博文主要来总结下SpringMVC中实现文件上传的步骤.但这里我只讲单个文 ...

  4. 使用SpringMVC框架实现文件上传和下载功能

    使用SpringMVC框架实现文件上传和下载功能 (一)单个文件上传 ①配置文件上传解释器 <!—配置文件上传解释器 --> <mvc:annotation-driven>&l ...

  5. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

  6. (H5)FormData+AJAX+SpringMVC跨域异步上传文件

    最近都没时间整理资料了,一入职就要弄懂业务,整天被业务弄得血崩. 总结下今天弄了一个早上的跨域异步上传文件.主要用到技术有HTML5的FormData,AJAX,Spring MVC. 首先看下上传页 ...

  7. SpringMvc入门五----文件上传

      知识点: SpringMvc单文件上传 SpringMvc多文件上传   这里我直接演示多文件上传,单文件的上传就不说了,不过代码都是现成的. 效果预览:   DEMO图:     添加文件上传j ...

  8. SpringMVC国际化与文件上传

    点击阅读上一章 其实SpringMVC中的页面国际化与上一章的验证国际化基本一致. 1.对页面进行国际化 1)首先我们对Spring配置文件中添加国际化bean配置 <!-- 注册国际化信息,必 ...

  9. SpringMVC框架06——文件上传与下载

    1.文件上传 Spring MVC框架的文件上传是基于commons-fileupload组件的文件上传,只不过Spring MVC框架在原有文件上传组件上做了进一步封装,简化了文件上传的代码实现. ...

随机推荐

  1. oracle 根据出生日期计算年龄的年月日

    select years,months,abs( trunc( newer_date- add_months( older_date,years*12+months ) ) ) days from ( ...

  2. PTA编程总结3—抓老鼠啊~亏了还是赚了?

    题目: 某地老鼠成灾,现悬赏抓老鼠,每抓到一只奖励10元,于是开始跟老鼠斗智斗勇:每天在墙角可选择以下三个操作:放置一个带有一块奶酪的捕鼠夹(T),或者放置一块奶酪(C),或者什么也不放(X).捕鼠夹 ...

  3. U3D外包团队:五款IDE推荐!

    1. Jetbrains RubyMine RubyMine是由捷克Jetbrains公司开发的,目前可提供使用的版本有RubyMine 5.4.而且RubyMine 5.4同时也为Rails 4的发 ...

  4. 安装xampp出错,windows找不到-n ?

    安装xampp出错,windows找不到-n ? https://www.zhihu.com/question/47248695/answer/105042516 尝试解决步骤 1.安装Microso ...

  5. C/C++.判断文件是否存在(_access)

    1. int _access(char* path,int mode)头文件<io.h>功能:确定文件或文件夹的访问权限.如果指定的存取方式有效,则函数返回0,否则函数返回-1. 参数pa ...

  6. Windows to go 慢,更换 user profile 路径

    用 wintousb 安装了 windwos 10 到 u盘 之后, 发觉这个windows 贼慢,卡的不行. 想起以前台式机上用[太阳花]SDD,硬盘满了也是这个感觉的. 就知道 C盘的userpr ...

  7. axios和promise

    什么是axios axios is a promise based HTTP client for the browser and node.js Features: Make XMLHttpRequ ...

  8. BluetoothGattCallback

    /** * 用于实现 BluetoothGatt 的回调 */public abstract class BluetoothGattCallback { /** * GATT客户端连接或断开到远程的时 ...

  9. 『TensorFlow』slim模块常用API

    辅助函数 slim.arg_scope() slim.arg_scope可以定义一些函数的默认参数值,在scope内,我们重复用到这些函数时可以不用把所有参数都写一遍,注意它没有tf.variable ...

  10. 一次完整的http事务的过程

    1.域名解析 2.发起TCP三次握手 3.建立TCP连接以后发起http请求 4.服务器端响应请求,浏览器得到html代码 5.浏览器解析html代码并请求html中的资源 6.浏览器对页面进行渲染呈 ...