Java文件上传和下载
1、页面
<center> <h1>文件上传</h1> <form name="uploadform"method="post" action="adddata" ENCTYPE="multipart/form-data"> <table border="1"width="450"cellpadding="4" cellspacing="2"bordercolor="#9BD7FF"> <tr><td width="100%"colspan="2"> 文件:<input name="file1"size="40"type="file"> </td></tr> </table> <table> <tr><td align="center"><input name="upload" type="submit"value="上传"/></td></tr> </table> </form> </center>
@SuppressWarnings("unchecked")public static String uploadFile(HttpServletRequest request) throws Exception{String path = "D:\\Temp";// 解析 request,判断是否有上传文件boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (isMultipart) {// 创建磁盘工厂,利用构造器实现内存数据储存量和临时储存路径DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4,new File(path));// 设置最多只允许在内存中存储的数据,单位:字节// factory.setSizeThreshold(4096);// 设置文件临时存储路径// factory.setRepository(new File("D:\\Temp"));// 产生一新的文件上传处理程式ServletFileUpload upload = new ServletFileUpload(factory);// 设置路径、文件名的字符集upload.setHeaderEncoding("UTF-8");// 设置允许用户上传文件大小,单位:字节upload.setSizeMax(1024 * 1024 * 100);// 解析请求,开始读取数据// Iterator<FileItem> iter = (Iterator<FileItem>)// upload.getItemIterator(request);// 得到所有的表单域,它们目前都被当作FileItemList<FileItem> fileItems = upload.parseRequest(request);// 依次处理请求Iterator<FileItem> iter = fileItems.iterator();while (iter.hasNext()) {FileItem item = (FileItem) iter.next();if (item.isFormField()) {// 如果item是正常的表单域String name = item.getFieldName();String value = item.getString("UTF-8");System.out.println("表单域名为:" + name + "表单域值为:" + value);} else {// 如果item是文件上传表单域// 获得文件名及路径String fileName = item.getName();if (fileName != null) {// 如果文件存在则上传File fullFile = new File(item.getName());if (fullFile.exists()) {path = path + "\" + fullFile.getName();File fileOnServer = new File(path);item.write(fileOnServer);System.out.println("文件" + fileOnServer.getName()+ "上传成功");}}}}}return path;}
try {String path = request.getRealPath("front\\software\")+File.separator+"name.exe";File file = new File(path);String filename = file.getName();InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();response.reset();response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}