【Java】后台将文件上传至远程服务器

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

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

客户端(文件上传):

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);
        }
    }

 

转载于:https://www.cnblogs.com/zwqh/p/9635176.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值