一个很简单实用的上传附件实例
首先主要用到的包:
先看服务端代码,我这里是用了Servlet,在web.xml配置
<servlet><servlet-class>com.file.FileEntryServlet</servlet-class><servlet-name>FileServlet</servlet-name></servlet><servlet-mapping><servlet-name>FileServlet</servlet-name><url-pattern>/fileEntry</url-pattern></servlet-mapping>
看服务端完整代码:
package com.file;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;import javax.servlet.ServletException;
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;@SuppressWarnings("serial")
public class FileEntryServlet extends HttpServlet
{@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{doPost(request, response);}@Override@SuppressWarnings("unchecked")public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{int state = 0;DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(4096);request.setCharacterEncoding("GBK");response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();ServletFileUpload upload = new ServletFileUpload(factory);upload.setSizeMax(1024 * 1024 * 10);//上传文件流try{String a = "";String b = "";HashMap fileMap = new HashMap();boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (isMultipart){try{List items = upload.parseRequest(request);Iterator iter = items.iterator();while (iter.hasNext()){FileItem item = (FileItem) iter.next();if (item.isFormField()){//普通文本信息处理 String paramName = item.getFieldName();String paramValue = item.getString();if ("a".equals(paramName))a = paramValue;else if ("b".equals(paramName))b = paramValue;}else{//上传文件信息处理 String fileName = item.getName();// String fileExt = this.getFileExt(fileName);String path = "/filetest";InputStream is = item.getInputStream();FileOutputStream fos = new FileOutputStream(path+"/"+ fileName);int index = 0;while((index=is.read())!=-1){fos.write(index);}is.close();fos.close();item.delete();//处理自己的业务System.out.println("a=="+a);System.out.println("b=="+b);//设置成功state=1;}}}catch (FileUploadException e){e.printStackTrace();}}if (state > 0)out.write("{'result':'true','message':'上传成功'}");out.flush();}catch (Exception e){//out.write("0");out.write("{'result':'false','message':'文件上传出现未知错误!'}");out.flush();out.close();//释放IO资源}}/*** 获取后缀名* @param vo*/private String getFileExt(String fileName) throws Exception{String value = new String();int start = 0;int end = 0;if (fileName == null)return null;start = fileName.lastIndexOf('.') + 1;end = fileName.length();value = fileName.substring(start, end);if (fileName.lastIndexOf('.') > 0)return value;elsereturn "";}
}
其中处理文本信息的代码:
处理附件的代码:
接下来是客户端调用代码:
package com.file;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;public class FileUpLoadUtil
{/*** 通过拼接的方式构造请求内容,实现参数传输以及文件传输* @param actionUrl 访问的服务器URL* @param params 普通参数* @param files 文件参数* @return* @throws IOException*/public static String post(String actionUrl, Map<String, String> params, String[] filePathList) throws IOException{String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";String result = "";URL uri = new URL(actionUrl);HttpURLConnection conn = (HttpURLConnection) uri.openConnection();conn.setReadTimeout(10 * 1000); // 缓存的最长时间conn.setDoInput(true);// 允许输入conn.setDoOutput(true);// 允许输出conn.setUseCaches(false); // 不允许使用缓存conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", CHARSET);conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);// 首先组拼文本类型的参数StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()){sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINEND);sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);sb.append("Content-Transfer-Encoding: 8bit" + LINEND);sb.append(LINEND);sb.append(entry.getValue());sb.append(LINEND);}DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(sb.toString().getBytes());// 发送文件数据 if (filePathList != null){for (String filePath : filePathList){File file = new File(filePath);StringBuilder sb1 = new StringBuilder();sb1.append(PREFIX);sb1.append(BOUNDARY);sb1.append(LINEND);sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINEND);sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);sb1.append(LINEND);outStream.write(sb1.toString().getBytes());InputStream is = new FileInputStream(file);byte[] buffer = new byte[1024 * 3];int len = 0;while ((len = is.read(buffer)) != -1){outStream.write(buffer, 0, len);}is.close();outStream.write(LINEND.getBytes());}}//请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();outStream.write(end_data);outStream.flush();int responseCode = conn.getResponseCode();if (HttpURLConnection.HTTP_OK == responseCode){StringBuffer returnInfo = new StringBuffer();String readLine;BufferedReader responseReader;responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));while ((readLine = responseReader.readLine()) != null){returnInfo.append(readLine).append("\n");}result = returnInfo.toString();responseReader.close();}return result;}public static void main(String[] args) throws Exception{String actionUrl = "http://localhost:8080/yszdServer/fileEntry";Map<String, String> params = new HashMap<String, String>();
// 参数params.put("a", "hahaha");params.put("b", "你好啊");//文件路径String[]支持多个String[] filePathList = { "d:\\123.txt" };//上传文件的路径String returns = FileUpLoadUtil.post(actionUrl, params, filePathList);System.out.println("服务端返回>>>" + returns);}
}
测试部分:
图中的3块分别传入“地址”“文本参数”“附件”,右键执行这个代码,服务打印出传入的参数a和b,如图:
同时也在指定的目录下生成了附件:
很简单方便,拿过去就可以调试使用,欢迎指正!!