springMvc---跨服务器文件上传(实测总结)

时间:2022-08-29 18:43:57

序言:

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

  springMvc---跨服务器文件上传(实测总结)

  

  file server's and point:

  springMvc---跨服务器文件上传(实测总结)

  you must confrim two server's point diffrence

 

上传后的文件:

  springMvc---跨服务器文件上传(实测总结)

页面回显:

  springMvc---跨服务器文件上传(实测总结)