亲宝软件园·资讯

展开

springMVC+jersey实现跨服务器文件上传

人气:0

1.首先添加所需要的jar包

 

2.在springMVC的配置文件中添加文件上传解析器

<!-- 文件上传的解析器 -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 文件上传大小的限制 -->
  <property name="maxUploadSize" value="5000000"></property>
  <property name="defaultEncoding" value="UTF-8"></property>
</bean>

3.jsp页面 

<form id="fm" action="" method="post">
 <p>
 <img src="" alt="" id="imgSrc"/>
 请上传头像:<input type="file" name="imgFile" id="imgFile" οnchange="fileUpload();"/>
 <input type="hidden" id="reletivePath" name="reletivePath" value="">
 </p>
</form>

4.文件上传的 js

 <!-- 文件上传js -->
<script type="text/javascript">
 function fileUpload(){
  var option = {
  type:"POST",
  url:"${pageContext.request.contextPath }/user/fileUpload.do",
  data:{
   fileName:"imgFile"
  },
  success:function(reData){
   alert(reData.reletivePath);
   $("#imgSrc").attr("height",100);
   $("#imgSrc").attr("width",100);
   $("#imgSrc").attr("src",reData.fullPath);
   $("#reletivePath").val(reData.reletivePath);
  },
  dataType:"json"
  };
  $("#fm").ajaxSubmit(option);
 }
</script>

5. controller

/*
 * 文件上传
 */
 @RequestMapping("fileUpload")
 public @ResponseBody Map<String , String> fileUpload(HttpServletRequest request,String fileName){
 System.out.println(111);
 //1.将普通请求转换为多部件请求
 MultipartHttpServletRequest mr = (MultipartHttpServletRequest)request;
 //2.根据文件名获取文件对象
 CommonsMultipartFile mf = (CommonsMultipartFile)mr.getFile(fileName);
 //3.获取文件全名称
 String originalFilename = mf.getOriginalFilename();
 System.out.println("文件全名称"+originalFilename);
 //4.获取后缀
 String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
 System.out.println("后缀"+suffix);
 //5.将文件对象转换为字节
 byte[] fileBytes = mf.getBytes();
 //6.获取新的随机文件名
 String newFileName="";
 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
 int num = (int)(Math.random()*899)+100;
 newFileName = sdf.format(new Date())+num;
 
 System.out.println("新的随机文件名"+newFileName);
 //开始上传
 //1.创建jesy服务器
 Client client = Client.create();
 String fullPath = "http://localhost:8088/fileServiceProject/upload/"+newFileName+suffix;
 //把文件关联到远程服务器
 WebResource wr = client.resource(fullPath);
 //2.相对路径
 String reletivePath = "/upload/"+newFileName+suffix;
 //3.上传
 wr.put(String.class, fileBytes);
 Map<String , String> map = new HashMap<String, String>();
 map.put("fullPath", fullPath);
 map.put("reletivePath", reletivePath);
 return map;
 }
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论