日期:2014-05-19 浏览次数:20716 次
public String upFile() throws Exception{ String targetURL = null;// TODO 指定URL File targetFile = null;// TODO 指定上传文件 System.out.println(config.getPath()); String str= new String(config.getPath().getBytes("iso8859-1"), "utf-8"); config.setPath(str); targetFile = new File(config.getPath()); targetURL = "http://localhost:8081/ftoa/upload"; //servleturl PostMethod filePost = new PostMethod(targetURL); System.out.println(targetFile); System.out.println(config.getPath()); System.out.println(filePost); try { //通过以下方法可以模拟页面参数提交 // filePost.setParameter("name", "中文"); // filePost.setParameter("pass", "1234"); System.out.println(targetFile.getName()); Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("上传成功"); configService.updataInfo(config); // 上传成功 } else { System.out.println("上传失败"); // 上传失败 } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } return null; }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); try { File tempfile = new File(System.getProperty("java.io.tmpdir")); // 采用系统临时文件目录 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempfile);// 设置缓冲区目录 tempPathFile ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);// 得到所有的文件 文件名是???? Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); fi.getString("UTF-8"); String fileName = fi.getName(); // response.setHeader("Content-disposition", "attachment;filename=" // + URLEncoder.encode(fileName, "UTF-8")); String str= new String(fileName.getBytes("ISO8859_1"), "utf-8"); fileName=str; System.out.println(fileName);//都是问号?????.txt if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } System.out.print("upload succeed"); } catch (Exception e) { System.out.println(e.getMessage()); // 可以跳转出错页面 e.printStackTrace(); } }