SSH+CKeditor下使用HttpClient实现文件的上传

简直*了狗了,老师需要我实现上传图片到远程文件服务器,说是为了负载均衡,资源同步,数据安全……balabala,理由能说出一大箩筐……

身为尊老爱幼的四好青年,毕竟老师带我那么久了,他说啥就是啥……所以干……

1、过程

各种问度娘,看博客,逛论坛……HttpClient 、HttpURLConnection、FTP、SFTP...好吧各种网络传输协议都试过一遍,发现自己还是回到原点……

自己智障的原因,懒……只想着把网上的代码复制下来,直接用,却没有好好的分析……

2、迷茫

忙活了一个星期,老师一直催,但一直没什么进展,一直想有个老司机带我飞多好,不过越这样想,越对自己都没信心了,痛定思痛……

3、希望

好吧,不能指望老司机了,还是得靠自己。使用谷歌,上github,认真查阅文档……和妹子聊天,妹子鼓励我,又重新对自己有了信心……
慢慢的自己有了头绪,正如《美队3》里面的反派所说,"只要有经验和耐心,任何事都可以做到……"
最后选择Http协议的理由:HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。
虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

  4、代码

本地服务器192:CkeditorUploadAction


PostMethod filePost = new PostMethod(URL_STR);
      HttpClient client = new HttpClient();
      String dirName = getUserInfo().getUsername();
      try {
          // 通过以下方法可以模拟页面参数提交
          Part[] parts = { new FilePart(dirName+'-'+trueName, toFile) };
          filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
          
          client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
          
          int status = client.executeMethod(filePost);
          if (status == HttpStatus.SC_OK) {
              System.out.println("上传成功");
          } else {
              System.out.println("上传失败");
          }
      } catch (Exception ex) {
          ex.printStackTrace();
      } finally {
          filePost.releaseConnection();
      }


远程服务器192:UploadFileServlet

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadFileServlet
 */
@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		try {
			processUpload(request,response);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
//	String uploadPath= "C:\\test\\";
	private static String uploadPath = "C:\\apache-tomcat-8.0.28-windows-x64\\webapps\\uploads\\";
	public void processUpload(HttpServletRequest request, HttpServletResponse response) throws FileUploadException{
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }

        System.out.println("Come on, baby .......");
        
        try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
        response.setCharacterEncoding("utf-8");  
          
        //检测是不是存在上传文件  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
          
        if(isMultipart){  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            
            //指定在内存中缓存数据大小,单位为byte,这里设为1Mb  
            factory.setSizeThreshold(1024*1024);  
           
            //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录   
            factory.setRepository(new File("C:\\temp"));  
            
            // Create a new file upload handler  
            ServletFileUpload upload = new ServletFileUpload(factory);  
           
            // 指定单个上传文件的最大尺寸,单位:字节,这里设为50Mb    
            upload.setFileSizeMax(50 * 1024 * 1024);    
            
            //指定一次上传多个文件的总尺寸,单位:字节,这里设为50Mb  
            upload.setSizeMax(50 * 1024 * 1024);     
            upload.setHeaderEncoding("UTF-8");
              
            List<FileItem> items  = upload.parseRequest(request);  
              
            
            if(items!=null){  
                //解析表单项目  
                Iterator<FileItem> iter = items.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = iter.next();
                    System.out.println("item...."+item);
                    System.out.println("item.getFileName()..."+item.getFieldName());
                    //如果是普通表单属性  
                    if (item.isFormField()) {  
                        //相当于input的name属性   <input type="text" name="content">  
                        String name = item.getFieldName();
                        //input的value属性  
                        String value = item.getString();

                        System.out.println("属性:" + name + " 属性值:" + value);  
                    }  
                    //如果是上传文件  
                    else {  
                        //属性名  
                        String fieldName = item.getFieldName();
                        String[] strarray=fieldName.split("-");
                        String newUploadPath =uploadPath+strarray[0];
                        File dirName = new File(newUploadPath);
                        if (!dirName.exists()) {
                        	dirName.mkdirs();
                        }
                        //上传文件路径  
                        String fileName = item.getName();  
                        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);// 获得上传文件的文件名  
                        
                        try {  
                            item.write(new File(newUploadPath, strarray[1]));  
                        } catch (Exception e) {  
                            e.printStackTrace();  
                        }  
                    } 
                }  
            }  
        }  
        
        response.addHeader("token", "hello");
    }
}






ps:网上很多都没有服务端的代码,太坑了,服务端注意需要两个jar文件,commons-fileupload-1.3.1.jar  以及 commons-io-2.5.jar
最后所需的jar,打包下载:链接:http://download.csdn.net/detail/sage_wang/9515110

原创:SH+CKeditor下使用HttpClient实现文件的上传


你可能感兴趣的:(图片,ssh,ckeditor)