利用jersey实现文件上传

maven依赖

<!-- 文件上传依赖 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- servlet依赖,用于接收多媒体文件-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
<!--jersey跨服务器上传依赖-->
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.19</version>
</dependency>

jersey工具类

public class JesyFileUploadUtil {

    /**
     * 上传文件
     *
     * @param file --文件名
     * @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {
        //重新设置文件名
        String newFileName = new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上
        //随机生成一个3位的随机数
        Random r = new Random();
        for(int i=0; i<3; i++) {
            newFileName += r.nextInt(10); //生成一个0-10之间的随机整数
        }

        //获取文件的扩展名
        String orginalFilename = file.getOriginalFilename();
        String suffix = orginalFilename.substring(orginalFilename.indexOf("."));

        //创建jesy服务器,进行跨服务器上传
        Client client = Client.create();
        //把文件关联到远程服务器
        //例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
        WebResource resource = client.resource(serverUrl+"/"+newFileName+suffix);
        //上传
        //获取文件的上传流
        resource.put(String.class, file.getBytes());

        //图片上传成功后要做的事儿
        //1、ajax回调函数做图片回显(需要图片的完整路径)
        //2、将图片的路径保存到数据库(需要图片的相对路径)
//        String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
        String relativePath = "/upload/"+newFileName+suffix; //相对路径

        return relativePath;
    }
}

另外附上相关的java文件

jersey工具类

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值