序言:

  该案例是采用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

上传后的文件:

  

页面回显:

  

最新文章

  1. LinqToDB 源码分析——DataContext类
  2. Linux 通过sendmail 发邮件到外部邮箱
  3. Linux内核分析第二周学习总结:操作系统是如何工作的?
  4. 【JavaScript】停不下来的前端,自动化流程
  5. 【nginx运维基础(4)】Nginx的日志管理(日志格式与定时分割日志)
  6. Codeforces 552E - Vanya and Brackets【表达式求值】
  7. java中数组与List相互转换的方法
  8. HDU 4421 ZOJ 3656 Bit Magic
  9. DOM操作中,遍历动态集合的注意事项。ex: elem.children
  10. MiseringThread.java 解析页面线程
  11. [翻译]Protocol Buffer 基础: C++
  12. AI 学习路线
  13. AE二次开发中几个功能速成归纳(符号设计器、创建要素、图形编辑、属性表编辑、缓冲区分析)
  14. return的作用
  15. 详细分析Java中断机制-转载
  16. bigdata learning unit two--Spark environment setting
  17. Python 标准异常总结
  18. Visual Studio资源汇总
  19. Mysql中字符串正确的连接方法
  20. &lt;welcome-file&gt;index.action&lt;/welcome-file&gt;直接设置action,404和struts2中的解决方案

热门文章

  1. Learning-Python【10】:函数初识
  2. POJ1141 Brackets Sequence---区间DP+输出路径
  3. npm发包注意
  4. 启动xampp出错,Port 80 in use by &quot;Unable to open process&quot; with PID 4!
  5. Zabbix4.0+第三方报警平台OneAlert监控报警
  6. Windows 用bat脚本带配置启动redis,并用vb脚本使其在后台运行。
  7. K8S中如何跨namespace 访问服务?为什么ping不通ClusterIP?
  8. DAY15 模块
  9. postman(六):详解在Pre-request Script中如何执行请求
  10. xxx征集系统项目目标文档