• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

jersey实现文件上传

武飞扬头像
zabaniya1886
帮助1

maven依赖

  1.  
    <!-- 文件上传依赖 -->
  2.  
    <dependency>
  3.  
    <groupId>commons-fileupload</groupId>
  4.  
    <artifactId>commons-fileupload</artifactId>
  5.  
    <version>1.3.1</version>
  6.  
    </dependency>
  7.  
    <!-- servlet依赖,用于接收多媒体文件-->
  8.  
    <dependency>
  9.  
    <groupId>javax.servlet</groupId>
  10.  
    <artifactId>javax.servlet-api</artifactId>
  11.  
    <version>3.1.0</version>
  12.  
    </dependency>
  13.  
    <!--jersey跨服务器上传依赖-->
  14.  
    <dependency>
  15.  
    <groupId>com.sun.jersey</groupId>
  16.  
    <artifactId>jersey-client</artifactId>
  17.  
    <version>1.19</version>
  18.  
    </dependency>
  19.  
    <dependency>
  20.  
    <groupId>com.sun.jersey</groupId>
  21.  
    <artifactId>jersey-core</artifactId>
  22.  
    <version>1.19</version>
  23.  
    </dependency>
学新通

jersey工具类

  1.  
    public class JesyFileUploadUtil {
  2.  
     
  3.  
    /**
  4.  
    * 上传文件
  5.  
    *
  6.  
    * @param file --文件名
  7.  
    * @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
  8.  
    * @return
  9.  
    * @throws IOException
  10.  
    */
  11.  
    public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {
  12.  
    //重新设置文件名
  13.  
    String newFileName = new Date().getTime() ""; //将当前时间获得的毫秒数拼接到新的文件名上
  14.  
    //随机生成一个3位的随机数
  15.  
    Random r = new Random();
  16.  
    for(int i=0; i<3; i ) {
  17.  
    newFileName = r.nextInt(10); //生成一个0-10之间的随机整数
  18.  
    }
  19.  
     
  20.  
    //获取文件的扩展名
  21.  
    String orginalFilename = file.getOriginalFilename();
  22.  
    String suffix = orginalFilename.substring(orginalFilename.indexOf("."));
  23.  
     
  24.  
    //创建jesy服务器,进行跨服务器上传
  25.  
    Client client = Client.create();
  26.  
    //把文件关联到远程服务器
  27.  
    //例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
  28.  
    WebResource resource = client.resource(serverUrl "/" newFileName suffix);
  29.  
    //上传
  30.  
    //获取文件的上传流
  31.  
    resource.put(String.class, file.getBytes());
  32.  
     
  33.  
    //图片上传成功后要做的事儿
  34.  
    //1、ajax回调函数做图片回显(需要图片的完整路径)
  35.  
    //2、将图片的路径保存到数据库(需要图片的相对路径)
  36.  
    // String fullPath = serverUrl "/upload/" newFileName suffix; //全路径
  37.  
    String relativePath = "/upload/" newFileName suffix; //相对路径
  38.  
     
  39.  
    return relativePath;
  40.  
    }
  41.  
    }
学新通

另外附上相关的java文件

jersey工具类

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhiaeaah
系列文章
更多 icon
同类精品
更多 icon
继续加载