环境 myEclipse9.1 servlet3.0
在网站中经常会遇到上传的功能,例如,用户上传自定义头像,上传共享资源,网站后台上传商品图片,如何实现此类功能? 现以上传图片为例,由客户端选择图片上传,服务器以字节流接受后,并保存在/images目录下,以jpg格式保存。
首先,如何让用户在客户端选择图片,在html中有表单对象标签
<form action="servlet/FileServlet" method="post"/>
上传图片:<input type="file" name="fileUp"/><input type="submit" value="上传"/>
</form>
由此可见input格式选为file则可以选择文件路径,
以下为服务器端代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("GBK");
String clientPath = request.getParameter("fileUp");
System.out.println(clientPath);
File clientFile = new File(clientPath);
FileInputStream inputStream = new FileInputStream(clientFile);
ServletContext context = this.getServletContext();
String serverPath = context.getRealPath(context.getContextPath());
String path = serverPath+"\\image";
File imgPath = new File(path);
System.out.println(imgPath.mkdir());
File fileImage = new File(path,clientFile.getName());
if(!fileImage.exists()){
fileImage.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(fileImage, true);
byte[] temp = new byte[128];
int size = (int)clientFile.length();
while(inputStream.read(temp)!=-1){
outputStream.write(temp, 0, temp.length);
}
outputStream.close();
inputStream.close();
}
首先我们用request接受到了客户端传送的路径,此路径是由客户端浏览器程序发送,(注意,此路径仅一次有效,) ,使用file创建了一个文件对象,之后我们通过环境上下文获取了项目的绝对路径,并拼出images的绝对路径,使用io流从客户端循环读一定量的字节,并写入文件。