文件的上传的部分源代码.

来源:互联网 发布:windows 便笺 编辑:程序博客网 时间:2024/05/21 10:35

//服务器客户端都记得导包

//客户端用post请求.

//服务器用dopost方法.

public  static String sendDataByHttpClientPost(String path , String name,String password ,String filepath) throws Exception{// 实例化上传数据的 数组  part []Part[] parts = {new StringPart("name", name),   new StringPart("password", password),   new FilePart("file", new File(filepath))};//得到filepost请求PostMethod filePost = new PostMethod(path);  //设置实体filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));//得到client.org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();        client.getHttpConnectionManager().getParams()          .setConnectionTimeout(5000);
//  发送数据.int status = client.executeMethod(filePost);if(status==200){System.out.println( filePost.getResponseCharSet());//得到返回的数据String result = new String(filePost.getResponseBodyAsString());//将返回的数据转经过转码后的到.String ha = new String ( result.getBytes("ISO-8859-1"),"UTF-8");System.out.println(ha);System.out.println("--"+result);return result;}else{throw new IllegalStateException("服务器状态异常");} }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//doGet(request, response);// 判断请求中是否包含文件.boolean isMultipart = ServletFileUpload.isMultipartContent(request);if(isMultipart){//若果有,得到文件上传的地址.String realpath = request.getSession().getServletContext().getRealPath("/files");System.out.println(realpath);//创建文件对象.File dir = new File(realpath);//若果目录不存在,目录创建.if(!dir.exists()) dir.mkdirs();//得到文件条目工厂factoryFileItemFactory factory = new DiskFileItemFactory();//将工厂塞给文件上传类.ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");try {//非常重要...文件上传类的到请求.为list集合. List<FileItem> items = upload.parseRequest(request);for(FileItem item : items){//遍历每一项.if(item.isFormField()){//若果是简单文本的话,就打印出来. String name1 = item.getFieldName(); String value = item.getString("UTF-8"); System.out.println(name1+ "="+ value);}else{//若果是文件类型,就把文件写到我的目录下.//System.currentTimeMillis()+ item.getName().substring(item.getName().lastIndexOf("."))为文件的名字//substring(item.getName().lastIndexOf(".")截取.后面的东西,如  时间.jpg.item.write(new File(dir, System.currentTimeMillis()+ item.getName().substring(item.getName().lastIndexOf("."))));}}response.getOutputStream().write("你好".getBytes("iso-8859-1"));} catch (Exception e) {e.printStackTrace();}}else{doGet(request, response);}}



0 0
原创粉丝点击