jersey实现跨服务器上传

1.导入跨服务器上传文件jar文件

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
</dependency>

 2.springmvc配置上传图片解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       
     <property name="maxUploadSize" value="1048576"/>
</bean>

 

 

 3.页面上传图片异步请求 ajax(实时回写)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!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">
<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 submitImgSize1Upload(){
    
    var option={
            type:'post',
            url:'${pageContext.request.contextPath}/upload/uploadPic.action',
            dataType:'text',
            data:{
                fileName:'imgSize1File'
            },
            success:function(data){
                
                var jsonObj = $.parseJSON(data);
                $("#imgSize1ImgSrc").attr("src",jsonObj.fullPath);
                
                $("#imgSize1").val(jsonObj.relativePath);
                
            }
            
        };

    $("#itemForm").ajaxSubmit(option);
}

</script>
<title>测试用的</title>
</head>
<body>
<form id="itemForm" action="${pageContext.request.contextPath}/upload/uploadPic.action" method="post">
<table width="100%" border=1>
<tr>
    <td>商品图片</td>
    <td>
        <p><label></label>
        <img id='imgSize1ImgSrc' src=''  height="100" width="100" />
        <input type='file' id='imgSize1File' name='imgSize1File' class="file" onchange='submitImgSize1Upload()' /><span class="pos" id="imgSize1FileSpan">请上传图片的大小不超过3MB</span>
<input type='hidden' id='imgSize1' name='pic' value='' reg="^.+$" tip="亲!您忘记上传图片了。" />
</p> </td> </tr> </table> </form> </body> </html>

 

 

 4.定义上传UploadControlle

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.fyh.www.common.SysContant;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/**
 * 使用ajax异步上传图片并回写图片
 * @author wumingsheng
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    
    @RequestMapping("/uploadPic")
    public void uploadPic(HttpServletRequest request,HttpServletResponse response,String fileName,PrintWriter out){
        //将普通请求转换为多部件请求方式
        MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
        //根据文件名进行获取文件对象
        CommonsMultipartFile cm = (CommonsMultipartFile) mh.getFile(fileName);
        //把多部件文件对象转换为字节
        byte[] fbytes = cm.getBytes();
        
        //定义文件名
        String newFileName="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        newFileName= sdf.format(new Date());
        //再加上三位随机数
        Random ran = new Random();
        for(int i=0;i<3;i++){
            
            newFileName = newFileName+ran.nextInt(10);
            
        }
        
        //获取上传文件的扩展名
        String suffix="";
        String originalFilename = cm.getOriginalFilename();
        suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        
        //创建jersy客户端
        Client client = Client.create();
        //指定关联文件图片服务器地址
        WebResource resource = client.resource(SysContant.PIC_HOST+"/upload/"+newFileName+suffix);
        //跨服务器上传图片
        resource.put(String.class, fbytes);
        
        String fullPath=SysContant.PIC_HOST+"/upload/"+newFileName+suffix;
        String relativePath="/upload/"+newFileName+suffix;
        
        //{"":"","":""}
        String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}";
        
        
        //ajax上传图片并回写
        
        out.print(result);
        
    }

}

 

 本案例中用本服务器作为了接受服务器:

public class SysContant {
 
    public static final String PIC_HOST = "http://localhost:8080/video";

}

 

 5.配置接受服务器的只读权限为false

 

posted @ 2016-10-26 10:14  woms  阅读(397)  评论(0编辑  收藏  举报