Linux下servlet上传文件

来源:互联网 发布:vs2017 连接mysql 编辑:程序博客网 时间:2024/06/07 01:08

我这里是使用了commons-io-1.4.jar,commons-fileupload-1.2.1.jar,这两个包。

具体代码如下

public void doPost(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {          request.setCharacterEncoding("utf-8");  //设置编码          //获得磁盘文件条目工厂          DiskFileItemFactory factory = new DiskFileItemFactory();        ServletFileUpload upload = new ServletFileUpload(factory);        try {              //可以上传多个文件              List items = upload.parseRequest(request);// 上传文件解析            Iterator itr = items.iterator();// 枚举方法            while (itr.hasNext()) {                FileItem item = (FileItem) itr.next();                if (item.isFormField()) {// 判断是文件还是文本信息                    System.out.println("表单参数名:" + item.getFieldName()                            + ",表单参数值:" + item.getString("UTF-8"));                } else {                    if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件                        System.out.println("上传文件的大小:" + item.getSize());                        System.out.println("上传文件的类型:" + item.getContentType());                        // item.getName()返回上传文件在客户端的完整路径名称                        System.out.println("上传文件的名称:" + item.getName());                        // 此时文件暂存在服务器的内存当中                        File tempFile = new File(item.getName());                        File file = new File("/home/he/workspace/Submission/upload/"+                                tempFile.getName());                        System.out.println(file.getPath());                        // 获取根目录对应的真实物理路径                        try {item.write(file);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}// 保存文件在服务器的物理磁盘中                        System.out.println("上传文件的名称:" + item.getName());                    } else {                        request.setAttribute("upload.message", "没有选择上传文件!");                    }                }            }                } catch (FileUploadException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }          catch (Exception e) {              // TODO Auto-generated catch block                            //e.printStackTrace();          }}
上传文件时在item.write(file)这一步会出现    text/htmljava.io.FileNotFoundException:  这个异常,这个是权限的问题,比如upload这个是上传文件夹,你只要chmod 777 upload 就ok


0 0
原创粉丝点击