将本地文件上传到远程服务器

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

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

客户端(文件上传):

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/Soy-technology/p/11652493.html

时间: 2024-08-04 07:42:14

将本地文件上传到远程服务器的相关文章

本地文件上传到Linux服务器的几种方法

本文介绍几种常见的方法,把文件上传到Linux服务器中! 常见有使用:scp命令.xshell软件里的xftp程序.U盘挂载.服务器自带的lrzsz程序. 一.scp使用说明: 1.把本机的文件传给目的服务器: scp get66.pcap [email protected]:/super 备注:把本机get66.pcap拷贝到147这台服务器的super目录下,需要提供147的密码 2.在本机上执行scp,把远端的服务器文件拷贝到本机上: scp [email protected]:/supe

将本地文件上传到远程git服务器

1.(先进入项目文件夹)通过命令 gitinit 把这个目录变成git可以管理的仓库 git init 2.把文件添加到本地版本库中,使用命令git add 文件:添加到暂存区里面去,如果后面接小数点".",意为添加文件夹下的所有文件 git add . 3.用命令 git commit告诉Git,把文件提交到仓库.引号内为提交说明 git commit -m 'first commit' 4.关联到远程库 git remote add origin 你的远程库地址 如: git re

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

在这里我们利用curl实现把本地服务器的文件通过curl发送请求给远程服务器的php文件接受就实现了上传,还一个是利用ftp来上传方法也是php中的curl操作ftp服务器进行上传. 我这里写的是用curl的代码 本地代码如下: <?php header('content-type:text/html;charset=utf8'); $curl = curl_init(); $data = array('img'=>'@'. dirname(__FILE__).'/img/login.gif'

将本地文件上传到远程库(二)

本地项目,右击选择Git bash here,进入到下面的界面 git init初始化一个git项目,初始化后本地项目会多出一个.git的文件 具体提交步骤完整如下: git remote add 分支名(自己取),然后把我的仓库换成你自己的仓库,最后push时输入你的用户名和密码 将修改了的本地文件同步到远程库: 修改task0003/js/task0003.js,然后将文件同步到远程库,通过上面的步骤已经将本地文件与目标远程库相关联,文件提交后可以直接push上去.先add再commit再p

SpringMVC结合Ajaxfileupload异步多文件上传至远程服务器

<input type="file" id="playeraddress" name="playeraddress" /> <input type="file" id="cover" name="cover" /> //这里就是两个file id自己定义 $.ajaxFileUpload({     url : web_path+'upload/upload.do

C# winform把本地文件上传到服务器上,和从服务器上下载文件

昨天在做项目过程中遇到需要把本地文件上传到服务器上的问题,在这里记录一下,方便大家互相学习! /// <summary> /// 上传文件方法/// </summary> /// <param name="filePath">本地文件所在路径(包括文件)</param> /// <param name="serverPath">文件存储服务器路径(包括文件)</param> public voi

将本地文件上传到指定的服务器(HttpWebRequest方法)

将本地文件上传到指定的服务器(HttpWebRequest方法),通过文件流,带文件名,同文件一同上传的表单文本域及值. 1 ///<summary> 2 /// 将本地文件上传到指定的服务器(HttpWebRequest方法) 3 /// </summary> 4 /// <param name="address">文件上传到的服务器</param> 5 /// <param name="fileNamePath&quo

scp. -本地文件上传服务器

scp 命令可以将本地文件上传服务器,或者将服务器上的文件下载到本地, 1.  上传服务器: scp [本地文件目录]  [服务器用户名]@[服务器名]:/[服务器上文件路径] 比如 scp /Documents/test.txt [email protected]服务器名:/home/optadmin/tmp/   将文件test.txt文件放到服务器上的tmp目录下 2.  下载本地 将服务器上的文件下载到本地时,只需要将上述 的两个路径互换即可 比如 scp  [email protect

JavaScript进阶 九 JS实现本地文件上传至阿里云服务器

JS实现本地文件上传至阿里云服务器 前言 在前面的博客< JavaScript进阶(八)JS实现图片预览并导入服务器功能>(点击查看详情)中,实现了JS将本地图片文件预览并上传至阿里云服务器的操作.这次需要实现将本地打包好的文件上传至阿里云服务器.使用前面的图片文件上传方法无法完成此操作.操作界面如下: 思路 本地与服务端传输文件的格式应该是熟悉的Base64格式.首先需要将本地文件转换为Base64格式,传输至服务端后,在服务端再将Base64格式的文件转换为原始文件. 源码解析 控制器 /