-
Java web中上传文件
- 先来看一下上传对form表单有什么要求?
- 必须是form表单提交。
- 表单中的method必须是post,不能是get
- 表单中的enctype的属性值必须是:multipart/form-data。当不是multipart的时候,就算<input type="file">提交的效果也和普通的text类型一样。
- 表单中项使用file类型
- 文件上传对servlet的要求?
- 因为表单中上传的不再是字符内容,而是字节内容。就算是上传文本文件也是一样的。所以不能使用request.getParameter(String fieldName)方法。
- 那使用什么呢。这个时候可以使用request.getInputStream();方法获取ServletInputStream对象,它是InputStream类的子类,这个对象对应表单的正文部分,关于正文部分下面会介绍。
- 关于正文部分介绍。
- 这个是有可以使用HTTP抓包工具,我使用的是Firebug。在Firefox进行抓包的。如下图所示:
![](https://img-blog.csdn.net/20130819143527968)
![](https://img-blog.csdn.net/20130819143652000)
- ServletInput中就包含第二张图片的内容。可以通过以下方法得到
- public void doPost(HttpServletRequest request,HttpServletResponse response)throw IOException,ServletException{
- request.setCharacterEncoding("utf-8");
- ServletInputStream in = request.getInputStream;
- String s = IOUtils.toString(in);
- System.out.println(s);
- }
和抓包来的没什么区别
- ------WebKitFormBoundaryH06xO2noLxVFeenm
- Content-Disposition: form-data; name="username"
- csdn
- ------WebKitFormBoundaryH06xO2noLxVFeenm
- Content-Disposition: form-data; name="filename"; filename="a.txt"
- Content-Type: text/plain
- E:\Application\workspace\exam\src\cn\itcast\day20\CountDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\FileDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\FileDemo2.java
- E:\Application\workspace\exam\src\cn\itcast\day20\FileDemo3.java
- E:\Application\workspace\exam\src\cn\itcast\day20\FileDemo4.java
- E:\Application\workspace\exam\src\cn\itcast\day20\FileFilterDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\JavaFileList.java
- E:\Application\workspace\exam\src\cn\itcast\day20\PrintWriterDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\PropertiesDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\SequenceDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\SequenceInputStreamDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\SequenceVideoDemo.java
- E:\Application\workspace\exam\src\cn\itcast\day20\SplitFileDemo.java
- ------WebKitFormBoundaryH06xO2noLxVFeenm--
。
上传的任务就是将这些信息解析出来如果是文件部分保存到文件中,不是文件部分该给谁给谁。
4.按照上面的上传文件中ServletInputStream流的格式我自己写了一个,只能上传文本文件的上传方法。(能力有限)
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- ServletInputStream in = request.getInputStream();
-
- int len = 0;
- byte buf[] = new byte[1024];
- String content = "";
- while((len = in.read(buf))!=-1){
- content = content + new String(buf, 0, len);
- }
-
- String[] contents = content.split("\n");
-
- List<String> lists = Arrays.asList(contents);
-
- System.out.println("执行:"+lists.contains(new String("Content-Type: text/plain")));
-
- int start = 0;
- int end = 0;
- for (int i=1;i<lists.size();i++) {
- if(lists.get(0).equals(lists.get(i))){
- end = i;
- }
- }
-
- System.out.println(start+":"+end);
-
- List<String> fileList = lists.subList(end+4, lists.size()-1);
-
- FileWriter writer = new FileWriter("F:\\a.txt");
-
- for (String s : fileList) {
- writer.write(s);
- writer.write("\n");
- }
- writer.close();
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request,response);
- }
使用Apache的commons组件包实现上传(还是这个强大):
- 快速入门(得到的效果和上面的一样):
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- ServletFileUpload fileUpload = new ServletFileUpload(factory);
- try {
-
- List<FileItem> items = fileUpload.parseRequest(request);
-
- for(FileItem item : items){
-
- if(item.getFieldName().equalsIgnoreCase("username")){
-
- System.out.println(item.getString());
-
- }else if(item.getFieldName().equalsIgnoreCase("fileName")){
-
- item.write(new File("F:\\","b.txt"));
- }
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- 完全体演示:
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
-
-
-
- request.setCharacterEncoding("utf-8");
-
-
-
-
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- ServletFileUpload fileUpload = new ServletFileUpload(factory);
-
-
-
-
- fileUpload.setFileSizeMax(300*1024);
-
-
-
- try {
-
- List<FileItem> items = fileUpload.parseRequest(request);
-
- for(FileItem item : items){
-
- if(item.getFieldName().equalsIgnoreCase("username")){
-
- System.out.println(item.getString());
-
- }else if(item.getFieldName().equalsIgnoreCase("fileName")){
-
- String fileName = item.getName();
-
- int index = fileName.lastIndexOf("\\");
- if(index!=-1){
- fileName = fileName.substring(index+1);
- }
-
-
- index = fileName.lastIndexOf(".");
-
- if(index==-1){
-
-
-
-
-
- System.out.println("上传的文件没有后缀名");
- return;
- }
-
- String extension = fileName.substring(index+1);
-
- if (!extension.equalsIgnoreCase("bmp")
- && !extension.equalsIgnoreCase("jpg")
- && !extension.equalsIgnoreCase("png")) {
-
- System.out.println("上传的文件必须是bmp或jpg或png");
- return;
- }
-
- fileName = getuuid()+"."+extension;
-
-
-
-
-
- String timeStamp = new SimpleDateFormat("yyyy.MM.dd").format(new Date());
- String savePath = this.getServletContext().getRealPath("/WEB-INF/myupload")+"\\"+timeStamp;
- File f = new File(savePath);
- f.mkdirs();
- item.write(new File(savePath,fileName));<pre name="code" class="java"><span style="white-space:pre"> </span>item.delete();
- "");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
- <pre></pre>
- <pre></pre>
- 如果还要判断上传文件的宽度和高度。只需在后面加上:
- <span style="white-space:pre"> </span>File f = new File(savePath);
- f.mkdirs();
- File saveFile = new File(savePath,fileName);
- item.write(saveFile);
- item.delete();
-
- ImageIcon icon = new ImageIcon(saveFile.getAbsolutePath());
- Image image = icon.getImage();
- image.getHeight(null);
- image.getWidth(null);
-
-
- saveFile.delete();
其他类型的文件也就类似了。