JavaWeb后台上传下载文件

有建议请留言,共同探讨。

public class FileUtil {
	//需要保存的目录 格式(/目录名)
	private String path;
	//保存的全路径
	private String savePath;
	//临时文件路径
	private String temPath="/temp";
	//缓冲区大小(b) 默认设置为10M
	private int bufferSize=1024*1024*10;
	//单个文件大小 单位(b) 默认设置为50M
	private long maxSize = (long)(1024*1024*50);
	//同时上传文件大小 单位(b) 默认设置为200M
	private long max = (long)(1024*1024*200);
	//允许上传的文件类型(后缀名) 默认设置为全部可以上传
	private List<String> fileSuffName = null;
	public List<String> getFileSuffName() {
		return fileSuffName;
	}
	public void setFileSuffName(List<String> fileSuffName) {
		this.fileSuffName = fileSuffName;
	}
	public String getTempPath() {
		return temPath;
	}

	public void setTempPath(String tempPath) {
		this.temPath = tempPath;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	public long getMax() {
		return max;
	}

	public void setMax(long max) {
		this.max = max;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
    /**
     * 上传文件
     * @param req 页面请求
     */
	public  void upload(HttpServletRequest req) {
		String realPath = req.getServletContext().getRealPath(path);
		String tempPath = req.getServletContext().getRealPath(temPath);
		File tempFile = new File(tempPath);
		File realFile = new File(realPath);
		if(!tempFile.exists()&&tempFile.isDirectory())
			tempFile.mkdirs();
		if(!realFile.exists()&&realFile.isDirectory()) {
			realFile.mkdirs();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();//创建工厂
		factory.setSizeThreshold(bufferSize);//设置缓冲区大小
		factory.setRepository(tempFile);//设置缓存目录
		ServletFileUpload upload = new ServletFileUpload(factory);//创建解析器
		upload.setProgressListener(new ProgressListener(){//监听事件
            @Override
            public void update(long pBytesRead, long pContentLength, int arg2) {
                System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
            }
        });
		upload.setHeaderEncoding("UTF-8");//设置文件名编码格式
		upload.setFileSizeMax(maxSize);//设置单个文件大小
		upload.setSizeMax(max);//设置上传多个文件的总共的大小
		try {
			List<FileItem> item = upload.parseRequest(req);
			for (FileItem fileItem : item) {
				if(fileItem.isFormField()) {//普通数据
					String name = fileItem.getName();
					String value =fileItem.getString("utf-8");
					System.out.println(name+":"+value);
				}else {//文件
					String name = fileItem.getName();
					System.out.println(name);
					if(name==null||name.trim().equals("")) {
						continue;
					}
					name=name.substring(name.lastIndexOf("\\")+1);
					String suffname=name.substring(name.lastIndexOf(".")+1);//文件后缀名
					String saveName = creatFileName(name);
					String savePath = realPath+File.separator+saveName;
					System.out.println(savePath);
					this.savePath=savePath;
					if(fileSuffName!=null) {
						for (String fileSuff : fileSuffName) {
							if(suffname.equals(fileSuff)) {
								fileItem.write(new File(savePath));
							}
						}
					}else {
						      fileItem.write(new File(savePath));
					}
					fileItem.delete();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {

		}
	}
	
	private String creatFileName(String name) {//生成唯一文件名
		return UUID.randomUUID().toString()+"_"+name;
	}
	/**
	 * 下载文件
	 * @param savaPath 文件绝对路径
	 * @param resp 响应
	 */
    public void download(String savaPath,HttpServletResponse resp) {
         String filename = savaPath.substring(savaPath.indexOf("_")+1);
       //设置响应头,告诉浏览器要下载的文件是否在浏览器中显示,inline表示内嵌显示,attachment表示弹出下载框
       resp.setHeader("Content-Disposition", "inline;filename="+filename);
       BufferedInputStream bis=null;
       OutputStream out=null;
       try {
	       bis = new BufferedInputStream(new FileInputStream(savaPath));
	       out = resp.getOutputStream();//获取输出流
	       int len=0;
	       while((len=bis.read())!=-1){
	       	out.write(len);//输出到客户端
	       }
           } catch (FileNotFoundException e) {
	          e.printStackTrace();
           }catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(out!=null)out.close();
				if(bis!=null)bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
   }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现JavaWeb上传图片并预览,可以按照以下步骤进行: 1. 在HTML页面中添加一个文件上传表单,例如: ``` <form action="upload.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="image" id="image"> <input type="submit" value="上传"> </form> ``` 2. 在后台Java代码中,处理文件上传并保存文件,例如: ``` Part filePart = request.getPart("image"); // 获取上传的文件 String fileName = UUID.randomUUID().toString() + "." + getFileExtension(filePart); // 生成文件名 String filePath = getServletContext().getRealPath("/uploads/") + fileName; // 生成文件保存路径 filePart.write(filePath); // 保存文件 ``` 其中,`getFileExtension`是一个自定义的方法,用于获取上传文件的扩展名。 3. 在HTML页面中,使用JavaScript预览上传的图片,例如: ``` <script> function previewImage() { var reader = new FileReader(); reader.onload = function(event) { document.getElementById("preview").setAttribute("src", event.target.result); }; reader.readAsDataURL(document.getElementById("image").files[0]); } </script> <img id="preview" src="" alt="预览图片"> <input type="file" name="image" id="image" onchange="previewImage()"> ``` 其中,`previewImage`是一个自定义的方法,用于预览上传的图片。该方法使用`FileReader`对象读取上传文件,并将其转换为DataURL,然后将DataURL设置为`<img>`标签的`src`属性,从而实现图片预览。 以上是一个简单的JavaWeb上传图片并预览的实现方式,你可以根据自己的需求进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值