• JavaWeb实现上传文件


    需要 commons-io与commons-fileupload 

    首先在jsp中创建一下布局
    1. <%@ page contentType="text/html;charset=UTF-8" language="java"%>
    2. <html>
    3. <head>
    4. <title>$Title$</title>
    5. </head>
    6. <body>
    7. <form action="MyServlet" method="post" enctype="multipart/form-data">
    8. 最简单的文件上传:<input type="file" name="fileupload"/>
    9. 描述:<input type="text" name="desc"/>
    10. <input type="submit" value="submit"/>
    11. </form>
    12. </body>
    13. </html>
    然后创建一个servlet类
    并在dopost方法中写入上传文件代码
    1. request.setCharacterEncoding("UTF-8");
    2. response.setCharacterEncoding("UTF-8");
    3. //1、创建一个DiskFileItemFactory工厂
    4. DiskFileItemFactory factory =newDiskFileItemFactory();
    5. //2、创建一个文件上传解析器
    6. ServletFileUpload upload =newServletFileUpload(factory);
    7. //解决上传文件名的中文乱码
    8. upload.setHeaderEncoding("UTF-8");
    9. factory.setSizeThreshold(1024*500);//设置内存的临界值为500K
    10. File linshi =newFile("E:\linshi");//当超过500K的时候,存到一个临时文件夹中
    11. factory.setRepository(linshi);
    12. upload.setSizeMax(1024*1024*5);//设置上传的文件总的大小不能超过5M
    13. try{
    14. // 1. 得到 FileItem 的集合 items
    15. List<FileItem>/* FileItem */items = upload.parseRequest(request);
    16. // 2. 遍历 items:
    17. for(FileItem item : items){
    18. // 若是一个一般的表单域, 打印信息
    19. if(item.isFormField()){
    20. String name = item.getFieldName();
    21. String value = item.getString("utf-8");
    22. System.out.println(name +": "+ value);
    23. }
    24. // 若是文件域则把文件保存到 e:\files 目录下.
    25. else{
    26. String fileName = item.getName();
    27. long sizeInBytes = item.getSize();
    28. System.out.println(fileName);
    29. System.out.println(sizeInBytes);
    30. InputStream in = item.getInputStream();
    31. byte[] buffer =newbyte[1024];
    32. int len =0;
    33. fileName ="e:\files\"+ fileName;//文件最终上传的位置
    34. System.out.println(fileName);
    35. OutputStream out =newFileOutputStream(fileName);
    36. while((len = in.read(buffer))!=-1){
    37. out.write(buffer,0, len);
    38. }
    39. out.close();
    40. in.close();
    41. }
    42. }
    43. }catch(FileUploadException e){
    44. e.printStackTrace();
    45. }
     
  • 相关阅读:
    禅道技术官网
    mysql中获取一天、一周、一月时间数据的各种sql语句写法
    使用HttpFileServer自建下载服务器
    axure新手入门教程
    Mysql存储过程查询结果赋值到变量的方法
    mysql 数据表中查找、删除重复记录
    oracle中的sql%rowcount,sql%found、sql%notfound、sql%rowcount和sql%isopen
    存储过程中的when others then 和 raise
    Oracle的DBMS_OUTPUT.PUT_LINE用法及脚本批处理方法
    oracle 特殊符号
  • 原文地址:https://www.cnblogs.com/crowsong/p/6362838.html
Copyright © 2020-2023  润新知