上传文件至远程服务器

4 篇文章 0 订阅

          最近学习了一个上传本地文件(.jpg、.png、.txt、.doc、.html、.jsp等等格式)到远程服务器的功能。

     写此功能自然想到了ajax的异步上传、token验证了。

     可以先写一个测试类,此处我就不写了,直接贴controller层上传代码了。

     /**
     * 上传文件
     */
    @RequestMapping("/postFile")
    @ResponseBody
    public Object postFile(HttpServletRequest request, @RequestParam("file")MultipartFile file) {
        Map<String, String> map = new HashMap<String, String>();
        if (!file.isEmpty()) {
            //获取文件名
            String fname = file.getOriginalFilename();
            //获取文件路径
            String suffix = comonUtil.getFileTypeExts(fname);//文件后缀
            String furl = UUID.randomUUID().toString() + suffix;
            map.put("fname", fname);
            map.put("furl", furl);
            
            String path = this.servletContext.getRealPath("/resource/"+fname);
            File tempFile = new File(path);    //将上传文件放到临时的resource目录下。
            try {
                file.transferTo(tempFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            int res_code =  postFile2Remote(furl, tempFile); //调用postFile2Remote方法
            if(res_code != 200){   //如果res_code=200(响应代码)时,上传成功。
                //失败
            }
            tempFile.delete();
        }
        return map;
    }


   /**
     * 上传文件至远程服务器
     */
    public int postFile2Remote(String uuidName, File file){
        int code =500;
        CloseableHttpClient httpclient = HttpClients.createDefault(); //创建一个httpclient
        try {
            HttpPost httppost = new HttpPost(Constant.REMOTE_FILESERVER_UPLOAD_URL);
            //REMOTE_FILESERVER_UPLOAD_URL此路径写在Constant类里面。
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("token", new StringBody(Constant.REMOTE_FILESERVER_TOKEN,ContentType.TEXT_PLAIN))//token验证
                    .addPart("path", new StringBody("qgg",ContentType.TEXT_PLAIN))
                    .addPart("fileName", new StringBody(uuidName,ContentType.TEXT_PLAIN))
                    .addPart("bin", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM,file.getName()))
                    .build();
            httppost.setEntity(reqEntity);
            
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                EntityUtils.consume(response.getEntity());
                code = response.getStatusLine().getStatusCode();
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return code;
    }


效果如下:


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值