JSP中的上载文件-如何更改上载文件的默认路径 [英] upload file in JSP - how to change a default path for the uploaded file

查看:86
本文介绍了JSP中的上载文件-如何更改上载文件的默认路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个jps页面来处理单个文件的上载. 这是用于选择文件的代码:

I have two jps pages to handle an upload of the single file. Here is a code for selecting a file:

 org.apache.commons.io.FilenameUtils, java.util.*, 
 java.io.File, java.lang.Exception" %>
...
 <form name="uploadFile" method="POST" action="processUpload.jsp"     
 enctype="multipart/form-data">
     <input type="file" name="myfile"><br />
     <input type="submit" value="Submit" />
 </form>
 ....

//--------处理上传的文件---------------------

//--------handle uploaded file---------------------

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>


<%
    System.out.println("Content Type ="+request.getContentType());
    System.out.println("Cookies" + request.getCookies());

    DiskFileUpload fu = new DiskFileUpload();
    // If file size exceeds, a FileUploadException will be thrown
    fu.setSizeMax(1000000);

    List fileItems = fu.parseRequest(request);
    Iterator itr = fileItems.iterator();

    while(itr.hasNext()) {
      FileItem fi = (FileItem)itr.next();

      //Check if not form field so as to only handle the file inputs
      //else condition handles the submit button input
      if(!fi.isFormField()) {
        System.out.println("\nNAME: "+fi.getName());
        System.out.println("SIZE: "+fi.getSize());
        //System.out.println(fi.getOutputStream().toString());
        File fNew= new File(application.getRealPath("/"), fi.getName());

        System.out.println(fNew.getAbsolutePath());
        fi.write(fNew);
      }
      else {
        System.out.println("Field ="+fi.getFieldName());
      }
    }
 %>

此代码将文件放入我的build \ web文件夹中. 如何设置服务器上其他目录的路径(假设设置了写权限)? 谢谢

This code put a file into my build\web folder. How to set a path to a different directory on the server (assuming the write permissions are set) ? Thanks,

推荐答案

使用以下代码(适用于

Use the following code (adapted for the user guide):

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(dir);

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload(factory);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);

这篇关于JSP中的上载文件-如何更改上载文件的默认路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆