简直*了狗了,老师需要我实现上传图片到远程文件服务器,说是为了负载均衡,资源同步,数据安全……balabala,理由能说出一大箩筐……
身为尊老爱幼的四好青年,毕竟老师带我那么久了,他说啥就是啥……所以干……
各种问度娘,看博客,逛论坛……HttpClient 、HttpURLConnection、FTP、SFTP...好吧各种网络传输协议都试过一遍,发现自己还是回到原点……
自己智障的原因,懒……只想着把网上的代码复制下来,直接用,却没有好好的分析……
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(); }
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"); } }