問題:由於系統在局域網(能訪問外網)內,但外網無法請求局域網內服務器文件和進行處理文件。
解決:建立文件服務器,用於存儲文件及外網調用。
客戶端(文件上傳):
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); } }