`

Servlet的文件上传代码(黄老师写得好,借鉴)

阅读更多
可惜单纯的<input type=file 已经不被支持,不过作为学习还是可以的
我的代码实现:(很乱的说)
			//完成图片上传,只能上传JPG 上传到tomcat目录底下
			String file = request.getParameter("file");
			if(file != ""){
				FileInputStream fin = new FileInputStream(file);
				byte[] picture = new byte[fin.available()];
				fin.read(picture);
				String picsPath = request.getRealPath("images") +"\\" + userName + ".jpg";
				dto.setPicsPath(picsPath); //保存路径
				FileOutputStream fout = new FileOutputStream(picsPath);
				fout.write(picture);
				fin.close();
				dto.setPics(picture);
			}
			//Add end


黄老师代码的实现
		// to store the image file
		File file = new File(picPath);
		if (file.exists()) {
			// begin to read the file from the path user input.
			FileInputStream fis = new FileInputStream(file);
			int fileSize = fis.available();
			byte[] fileBytes = new byte[fileSize];
			fis.read(fileBytes);
			fis.close();// don't forget to close the stream.

			// so far, the file are read in fileBytes array.
			// now, begin to write the data to the parth which are fixed in
			// server.
			// getServletContext() method is the method from the parent of this
			// class.
			String serverDir = getServletContext().getRealPath("image");
			String filePath = serverDir + "\\" + file.getName();
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(fileBytes);
			fos.close();// don't forget to close the stream.

			// well, the file is upload to /image/xxx.xx
			// so we set the picture path to /image/xxx.xx
			dto.setPicPath("/image/" + file.getName());
		}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics