【Java】バックグラウンドでファイルをリモートサーバにアップロード

20048 ワード

問題:システムはローカルエリアネットワーク(外部ネットワークにアクセス可能)内にあるため、外部ネットワークはローカルエリアネットワーク内のサーバファイルと処理ファイルを要求できません.
解決:ファイルおよび外部ネットワーク呼び出しを格納するファイルサーバを確立します.
クライアント(ファイルアップロード):
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 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 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 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 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 param=new HashMap();
        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 map = new HashMap();
        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);
        }
    }