问题:由于系统在局域网(能访问外网)内,但外网无法请求局域网内服务器文件和进行处理文件。

解决:建立文件服务器,用于存储文件及外网调用。

客户端(文件上传):

package cn.hkwl.lm.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class UploadToServer {
private static final Logger log = LoggerFactory.getLogger(UploadToServer.class); public static String postFile(String url,Map<String, Object> param, File file) throws ClientProtocolException, IOException {
String res = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(getMutipartEntry(param,file));
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
res = EntityUtils.toString(entity, "UTF-8");
response.close();
} else {
res = EntityUtils.toString(entity, "UTF-8");
response.close();
throw new IllegalArgumentException(res);
}
return res;
} private static MultipartEntity getMutipartEntry(Map<String, Object> param, File file) throws UnsupportedEncodingException {
if (file == null) {
throw new IllegalArgumentException("文件不能为空");
}
FileBody fileBody = new FileBody(file);
FormBodyPart filePart = new FormBodyPart("file", fileBody);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart(filePart); Iterator<String> iterator = param.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
FormBodyPart field = new FormBodyPart(key, new StringBody((String) param.get(key)));
multipartEntity.addPart(field); }
return multipartEntity;
} }

服务器端(文件接收):

package cn.hkwl.office.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.springframework.stereotype.Controller;
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.CommonsMultipartResolver; import cn.zy.action.BaseAction; @Controller
@RequestMapping("/file")
public class FileAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = -5865227624891447594L; @RequestMapping("/receive")
public @ResponseBody void receive(HttpServletRequest request,
HttpServletResponse response) throws Exception {
JSONObject json=new JSONObject();
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator<String> iter = multiRequest.getFileNames(); // 定义绝对路径
String localPath = getRealPath("/upload/lm");
File path = new File(localPath);
// 文件夹不存在 则创建文件夹
if (!path.exists()) {
path.mkdir();
} while (iter.hasNext()) {
// 一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next()
.toString());
if (file != null) {
String filepath = localPath +File.separator+ file.getOriginalFilename();
// 上传
file.transferTo(new File(filepath));
// 文件数据存储起来
json.put("success", true);
json.put("httpUrl", "http://serverhostip:9080/lmoffice/upload/lm/"+file.getOriginalFilename());
}
} }else{
json.put("success", false);
}
outJson(json);
} }

应用使用:

    private String getHttpUrl(String savePath) throws ClientProtocolException, IOException{
File file=new File(getRealPath(savePath));
System.out.println(file.exists());
Map<String,Object> param=new HashMap<String, Object>();
String res=UploadToServer.postFile("http://serverhostip:9080/lmoffice/file/receive",param,file);
JSONObject result=JSONObject.fromObject(res);
if(result.getBoolean("success")){
file.delete();//删除本地文件
return result.getString("httpUrl");
}
return ""; } /***
* 管线迁移公告
*
* @param landId
*/
@RequestMapping("/gxqygg.do")
public @ResponseBody
void createGXQYGG(Long landId) {
JSONObject json = new JSONObject();
Land land = landService.getLandInfo(landId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("land", land);
Calendar calendar = Calendar.getInstance();// 取当前日期。
map.put("year", calendar.get(Calendar.YEAR) + "");
map.put("month",
(calendar.get(Calendar.MONTH) + 1 > 12 ? calendar
.get(Calendar.MONTH) - 11 : calendar
.get(Calendar.MONTH) + 1)
+ "");
map.put("day", calendar.get(Calendar.DATE) + "");
try {
//通过freemark动态生成word文件
String savePath = WordUtils
.exportMillCertificateWordReturnSavePath(getRequest(),
getResponse(), map, "管线迁移公告", "gxqygg.ftl",
"word/gxqygg"); json.put("success", true);
json.put("savePath",getHttpUrl(savePath));//获取上传后网络路径
outJson(json);
} catch (Exception e) {
e.printStackTrace();
json.put("success", false);
json.put("error", e.toString());
outJson(json);
}
}

【Java】后台将文件上传至远程服务器的更多相关文章

  1. java后台调用文件上传接口

    借鉴:https://blog.csdn.net/yjclsx/article/details/70675057 /** * 调用流程上传文件接口上传文件 * @param url * @param ...

  2. php把文件上传到远程服务器上例子

    在这里我们利用curl实现把本地服务器的文件通过curl发送请求给远程服务器的php文件接受就实现了上传,还一个是利用ftp来上传方法也是php中的curl操作ftp服务器进行上传. 我这里写的是用c ...

  3. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  4. Java实现FTP文件上传与下载

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cl ...

  5. Java FTPClient实现文件上传下载

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  6. Java中实现文件上传下载的三种解决方案

    第一点:Java代码实现文件上传 FormFile file=manform.getFile(); String newfileName = null; String newpathname=null ...

  7. 【原创】用JAVA实现大文件上传及显示进度信息

    用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/grayprince/UploadBigFil ...

  8. Java下载https文件上传到阿里云oss服务器

    Java下载https文件上传到阿里云oss服务器 今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 .实现自己的证书信任管理器类 /** ...

  9. 【Java】JavaWeb文件上传和下载

    文件上传和下载在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件 ...

随机推荐

  1. 分布式Id - redis方式

    本篇分享内容是关于生成分布式Id的其中之一方案,除了redis方案之外还有如:数据库,雪花算法,mogodb(object_id也是数据库)等方案,对于redis来说是我们常用并接触比较多的,因此主要 ...

  2. java架构之路-(11)JVM的对象和堆

    上次博客,我们说了jvm运行时的内存模型,堆,栈,程序计数器,元空间和本地方法栈.我们主要说了堆和栈,栈的流程大致也说了一遍,同时我们知道堆是用来存对象的,分别年轻代和老年代.但是具体的堆是怎么来存放 ...

  3. Golang error 的突围

    目录 error 的困局 尝试破局 Errors are just values handle not just check errors Only handle errors once 小结 胎死腹 ...

  4. 行数据库VS列数据库

    一.介绍 目前大数据存储有两种方案可供选择:行存储和列存储.业界对两种存储方案有很多争持,集中焦点是:谁能够更有效地处理海量数据,且兼顾安全.可靠.完整性.从目前发展情况看,关系数据库已经不适应这种巨 ...

  5. Java反序列化漏洞原理解析(案例未完善后续补充)

    序列化与反序列化 序列化用途:方便于对象在网络中的传输和存储 java的反序列化 序列化就是将对象转换为流,利于储存和传输的格式 反序列化与序列化相反,将流转换为对象 例如:json序列化.XML序列 ...

  6. DNA sequence(映射+BFS)

    Problem Description The twenty-first century is a biology-technology developing century. We know tha ...

  7. Single Number 普通解及最小空间解(理解异或)

    原题目 Given a non-empty array of integers, every element appears twice except for one. Find that singl ...

  8. LinkedHashSet集合

    LinkedHashSet集合与HashSet集合的最大区别在于,LinkedHashSet集合存入和取出的顺序相同,而HashSet集合存取顺序不一定相同: import java.util.Has ...

  9. Linux环境下进行分布式压测踩过的坑

    背景:公司为了满足大并发的情况,需要测试组配合,就需要分布式压测,这里我把我踩过坑都记录下来: 环境:Linux + jmeter-v.5.1.1;使用3台2核4G的压力机: Q1: Server f ...

  10. python 虚拟环境下导入模块出现no matching modules 的解决办法

    问题原因:pip版本过低 解决办法:升级pip                             命令行为   python -m pip install -U pip