最近学struts2的上传文件,总是出问题?请各位帮忙一下?在下不甚感激

解决方案 »

  1.   

    给你个简单的例子view层的代码(这里是jsp页面):<tr>
    <td width="15%">焦点图片:</td>
    <td colspan="3" width="85%" class="pn-fcontent">
             <s:file name="picture" size="80"/
    </td>
    </tr>
    action 中的代码: // 上传图片的三个封装的属性 名字必须是 xxxx,xxxContentType,xxxxFileName
    private File picture; 
    private String pictureContentType;
    private String pictureFileName;
             
            //省略getter and  setter method        //执行上传操作
             // 上传标题图片
    if (null != pictureFileName && pictureFileName.trim().length() > 0) {
    //先将文件重新命名
    String tempFileName = CommonUtils.reName(pictureFileName);
    String dir = ServletActionContext.getServletContext().getRealPath("/upload/image");
    File dirs = new File(dir);
    if (!dirs.exists()) {
    dirs.mkdir();
    }
    String picturePath = dir + "/" + tempFileName;
    File imageFile = new File(picturePath);
    try {
                                    //执行文件的拷贝
    CommonUtils.copyFile(picture, imageFile); // 拷贝文件到服务器 } catch (Exception e) {
    e.printStackTrace();
    } }
    CommonUtils工具类中的reName静态方法和copyFile静态方法描述如下: // 使用uuid 重名名文件
    public static String reName(String fileName) {
    String newFileName = null;
    int index = fileName.lastIndexOf('.');
    if (index != -1) {
    newFileName = UUID.randomUUID().toString() + fileName.substring(index);
    } else
    newFileName = UUID.randomUUID().toString(); return newFileName;
    }
            /**
     * 拷贝文件
     */
    public static void copyFile(File source, File destination) throws Exception {
    try {
    InputStream in = null;
    OutputStream out = null;
    try {
    in = new BufferedInputStream(new FileInputStream(source), BUFFER_SIZE);
    out = new BufferedOutputStream(new FileOutputStream(destination), BUFFER_SIZE);
    byte[] buf = new byte[BUFFER_SIZE];
    while (in.read(buf) > 0) {
    out.write(buf);
    }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (in != null)
    in.close();
    if (out != null)
    out.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    throw new Exception(e);
    } }
      

  2.   

    利用fealupload.jar  网上搜一下 这种东西多得是
      

  3.   

    哥真是服了你,这样也能成为程序员。百度不行,就去Google。
      

  4.   

    这里有我写的源码,上传下载都有:http://download.csdn.net/source/2811119不懂加我QQ:505112104  咨询
      

  5.   

    以前也写过,但好久没用了,忘掉了。
    LZ需要的话可以发邮箱到[email protected],可以提供案例。LZ可以加入59673719(IT精英)群,大家相互交流意见,