`
奥义之舞
  • 浏览: 281604 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java文件上传和下载

    博客分类:
  • 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>  

要实现文件上传,在form标签内必须包含 ENCTYPE="multipart/form-data" 才可以实现(RFC1867协议:http://www.faqs.org/rfcs/rfc1867.html),且必须以 POST 方式上传。
2、Servelt 实现(commons-fileupload-1.2.1、commons-io-1.4)
根据Action自己配置相应路径
@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);
			// 得到所有的表单域,它们目前都被当作FileItem
			List<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;
	}

利用ccommons-fileupload-1.2.1实现上传,其实现必须包含commons-io-1.4,以上为我实现上传文件所使用的方法和所用到包的版本。

总结:以正常实现文件上传功能,在实现过程中如果form未配置 ENCTYPE="multipart/form-data" 元素,
则上传文件为本地的绝对路径,而非正常的文件。
详细使用参考api文档。

相应JAR包见附件



------------------------------------------------------------------------------
看到有很多朋友也在找下载的东西,特地把我项目当中的下载程序共享

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();
		}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics