java上传文件到远程服务器(二)---HttpClient方式

142 篇文章 2 订阅
47 篇文章 1 订阅



我们已经在上一篇文章中讲解了把文件上传到远程服务器的一种方式:


java上传文件到远程服务器(一)---HttpURLConnection方式


本章来尝试使用HttpClient方式上传文件到远程服务器:

我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录HttpURLConnection上传文件到远程服务器。

应用bootstrap模板


基础项目源码下载地址为:

SpringMVC+Shiro+MongoDB+BootStrap基础框架


我们在基础项目中已经做好了首页index的访问。
现在就在index.jsp页面和index的路由Controller上做修改,HttpClient上传文件到远程服务器。




客户端



客户端HttpClient上传文件到远程服务器的原理是通过构造参数模仿form提交文件的http请求,把文件提交到远程服务器的接收路由中。


index.jsp的代码为:

<%@ include file="./include/header.jsp"%>
        <div id="page-wrapper">
            <div id="page-inner">


                <div class="row">
                    <div class="col-md-12">
                        <h1 class="page-header">
                            HttpURLConnection <small>HttpURLConnection</small>
                        </h1>
                    </div>
                </div>
                <!-- /. ROW  -->

     <form class="form-horizontal" name="upform" action="upload" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                    <label for="sourceModule" class="col-sm-2 control-label">上传文件:</label>
                    <div class="col-sm-10">
                  <input type="file" name="filename"/><br/>  
                                               <input type="submit" value="提交" /><br/> 
                    </div>
                </div>
           </form>  
                <!-- /. ROW  -->
            </div>
            <!-- /. PAGE INNER  -->
        </div>
        <!-- /. PAGE WRAPPER  -->

    

        
        


 <%@ include file="./include/footer.jsp"%>

<script type="text/javascript">
    $(document).ready(function () {
   

    });

</script>


</body>

</html>



需要httpclient的包,我这里使用的是httpclient4.3.3.jar和httpmime4.3。

如果使用的是maven则在pom.xml中添加:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>


路由中upload方法接受form提交的file文件,并且上传到服务器:

IndexController.java代码如下:

package com.test.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * IndexController
 * 
 * 
 */
@Controller
public class IndexController {

	private static final String FAR_SERVICE_DIR = "http://192.168.30.39:8080/receive";// 远程服务器接受文件的路由
	private static final long yourMaxRequestSize = 10000000;

	@RequestMapping("/")
	public String index(Model model) throws IOException {

		return "/index";
	}

	@RequestMapping("/upload")
	public String upload(HttpServletRequest request) throws Exception {
		// 判断enctype属性是否为multipart/form-data
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart)
			throw new IllegalArgumentException(
					"上传内容不是有效的multipart/form-data类型.");

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// 设置上传内容的大小限制(单位:字节)
		upload.setSizeMax(yourMaxRequestSize);

		// Parse the request
		List<?> items = upload.parseRequest(request);

		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();

			if (item.isFormField()) {
				// 如果是普通表单字段
				String name = item.getFieldName();
				String value = item.getString();
				// ...
			} else {
				// 如果是文件字段
				String fieldName = item.getFieldName();
				String fileName = item.getName();
				String contentType = item.getContentType();
				boolean isInMemory = item.isInMemory();
				long sizeInBytes = item.getSize();
				// ...

				// 上传到远程服务器
				HashMap<String, FileItem> files = new HashMap<String, FileItem>();
				files.put(fileName, item);
				uploadToFarServiceByHttpClient(files);
			}
		}
		return "redirect:/";
	}

	private void uploadToFarServiceByHttpClient(HashMap<String, FileItem> files) {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost httppost = new HttpPost(FAR_SERVICE_DIR);
			MultipartEntity reqEntity = new MultipartEntity();
			Iterator iter = files.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = (String) entry.getKey();
				FileItem val = (FileItem) entry.getValue();
				FileBody filebdody = new FileBody(inputstreamtofile(
						val.getInputStream(), key));
				reqEntity.addPart(key, filebdody);
			}
			httppost.setEntity(reqEntity);

			HttpResponse response = httpclient.execute(httppost);

			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == HttpStatus.SC_OK) {
				System.out.println("服务器正常响应.....");
				HttpEntity resEntity = response.getEntity();
				System.out.println(EntityUtils.toString(resEntity,"UTF-8"));// httpclient自带的工具类读取返回数据
				EntityUtils.consume(resEntity);
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				httpclient.getConnectionManager().shutdown();
			} catch (Exception ignore) {

			}
		}

	}

	public File inputstreamtofile(InputStream ins, String filename)
			throws IOException {
		File file = new File(filename);
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
		return file;
	}

}


服务端



我们仍然在基础项目上fileController中实现接收文件。代码如下:
FileController.java

package com.test.web.controller;  
  
import java.io.File;  
import java.util.Iterator;  
import java.util.List;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
/** 
 * IndexController 
 *  
 *  
 */  
@Controller  
public class FileController {  
  
    //private static final String STORE_FILE_DIR="/usr/local/image/";//文件保存的路径  
    private static final String STORE_FILE_DIR="D:\\";//文件保存的路径  
  
    @RequestMapping("/receive")  
    public String receive(HttpServletRequest request,HttpServletResponse response) throws Exception {  
        // 判断enctype属性是否为multipart/form-data  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
        if (!isMultipart)  
            throw new IllegalArgumentException(  
                    "上传内容不是有效的multipart/form-data类型.");  
  
        // Create a factory for disk-based file items  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
  
        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory);  
  
        // Parse the request  
        List<?> items = upload.parseRequest(request);  
  
        Iterator iter = items.iterator();  
        while (iter.hasNext()) {  
            FileItem item = (FileItem) iter.next();  
            if (item.isFormField()) {  
                // 如果是普通表单字段  
                String name = item.getFieldName();  
                String value = item.getString();  
                // ...  
            } else {  
                // 如果是文件字段  
                String fieldName = item.getFieldName();  
                String fileName = item.getName();  
                String contentType = item.getContentType();  
                boolean isInMemory = item.isInMemory();  
                long sizeInBytes = item.getSize();  
                  
                String filePath=STORE_FILE_DIR+fileName;  
                //写入文件到当前服务器磁盘  
                File uploadedFile = new File(filePath);  
                // File uploadedFile = new File("D:\haha.txt");  
                item.write(uploadedFile);  
            }  
        }  
        response.setCharacterEncoding("UTF-8");    
         response.getWriter().println("上传成功");  
        return null;  
    }  
  
}  

我们需要把服务端发布到 远程服务器上 使用tomcat等运行起来。
如果项目中有shiro拦截的话记得设置成  /receive = anon 。让接收文件的路由不被拦截。
然后运行客户端,选择文件就可以上传了。对安全有要求的,可以在客户端加一个key,服务器端接收到请求后验证key,没问题的话 再写入目录和文件。




Java可以使用URLConnection类或者Apache HttpClient库来读取远程服务器的文件列表。 1. 使用URLConnection类: 首先,创建一个URL对象,指定要访问的远程服务器地址。然后,使用URL对象的openConnection()方法打开一个连接,并转换为HttpURLConnection对象。接着,设置HTTP请求的方法(GET、POST等)、超时时间等属性,并连接到远程服务器。通过getInputStream()方法获取远程服务器的响应数据流,并使用BufferedReader逐行读取文件列表。 以下是示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class RemoteFileReader { public static void main(String[] args) { try { URL url = new URL("https://example.com/filelist"); // 替换为实际的远程服务器地址 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); // 设置连接超时时间为5秒 connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); // 输出远程服务器的文件列表 } reader.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用Apache HttpClient库: 首先,引入Apache HttpClient库的相关依赖。然后,创建一个HttpClient对象,并使用HttpGet请求指定的远程服务器地址。通过调用execute()方法发送请求并获取响应。使用EntityUtils类将响应的实体转换为字符串,并解析获取文件列表信息。 以下是示例代码: ``` import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class RemoteFileReader { public static void main(String[] args) { try { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://example.com/filelist"); // 替换为实际的远程服务器地址 HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); String filelist = EntityUtils.toString(entity); // 获取文件列表字符串 System.out.println(filelist); // 输出远程服务器的文件列表 httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 无论是使用URLConnection类还是Apache HttpClient库,需要替换示例代码中的远程服务器地址为实际的地址。在实际应用中,可能需要根据远程服务器的访问授权、协议、端口等设置相关参数。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小凡vip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值