java中图片上传和服务器虚拟目录配置

FileUpload 是 Apache commons下面的一个子项目,用来实现Java环境下面的文件上传功能,与常见的SmartUpload齐名。

upload.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form name="itemForm" target="_self" id="itemForm" method="post"
        action="FileUpLoad" enctype="multipart/form-data">
        <table border="0" class="perview" align="center">
            <tr>
                <td height="200"><input name="fileName" type="file"
                    class="text1" size="40" maxlength="40"></td>
                <td height="200"><input name="fileName" type="file"
                    class="text1" size="40" maxlength="40"></td>    
            </tr>
            <tr>
                <td><input type="submit" value="提交" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


FileUpLoad.java

package edu.cslg.huachen.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpLoad
 */
@WebServlet("/FileUpLoad")
public class FileUpLoad extends HttpServlet {
    private File uploadPath;

    private File tempPath;

    @Override
    public void init() throws ServletException {
        // 在系统启动的时候,就开始初始化,在初始化时,检查上传图片的文件夹和存放临时文件的文件夹是否存在,如果不存在,就创建

        // 获取根目录对应的真实物理路径
        uploadPath = new File(getServletContext().getRealPath("upload"));
        System.out.println(getServletContext().getRealPath("/s/a"));
        
        System.out.println("uploadPath=====" + uploadPath);
        // 如果目录不存在
        if (!uploadPath.exists()) {
            // 创建目录
            uploadPath.mkdir();
        }

        // 临时目录
        // File tempFile = new File(item.getName())构造临时对象
        tempPath = new File(getServletContext().getRealPath("temp"));
        if (!tempPath.exists()) {
            tempPath.mkdir();
        }

        // 如果不显示调用父类方法,就不会有itemManager实例,因此会造成空指针
        super.init();

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 从item_upload.jsp中拿取数据,因为上传页的编码格式跟一般的不同,使用的是enctype="multipart/form-data"
        // form提交采用multipart/form-data,无法采用req.getParameter()取得数据
        // String itemNo = req.getParameter("itemNo");
        // System.out.println("itemNo======" + itemNo);

        /******************************** 使用 FileUpload 组件解析表单 ********************/

        // DiskFileItemFactory:创建 FileItem 对象的工厂,在这个工厂类中可以配置内存缓冲区大小和存放临时文件的目录。
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        factory.setRepository(tempPath);

        // ServletFileUpload:负责处理上传的文件数据,并将每部分的数据封装成一到 FileItem 对象中。
        // 在接收上传文件数据时,会将内容保存到内存缓存区中,如果文件内容超过了 DiskFileItemFactory 指定的缓冲区的大小,
        // 那么文件将被保存到磁盘上,存储为 DiskFileItemFactory 指定目录中的临时文件。
        // 等文件数据都接收完毕后,ServletUpload再从文件中将数据写入到上传文件目录下的文件中

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        upload.setSizeMax(1000000 * 20);

        /******************************* 解析表单传递过来的数据,返回List集合数据-类型:FileItem ***********/

        try {

            List fileItems = upload.parseRequest(request);

            String itemNo = "";
            // Iterator iter = fileItems.iterator()取其迭代器
            // iter.hasNext()检查序列中是否还有元素
            for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
                // 获得序列中的下一个元素
                FileItem item = (FileItem) iter.next();

                // 判断是文件还是文本信息
                // 是普通的表单输入域
                if (item.isFormField()) {
                    if ("itemNo".equals(item.getFieldName())) {
                        itemNo = item.getString();
                        System.out.println("c");
                    }
                }
                // 是否为input="type"输入域
                if (!item.isFormField()) {
                    // 上传文件的名称和完整路径
                    String fileName = item.getName();
                    System.out.println(fileName);

                    long size = item.getSize();
                    // 判断是否选择了文件
                    if ((fileName == null || fileName.equals("")) && size == 0) {
                        continue;
                    }
                    // 截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
                    fileName = fileName.substring(
                            fileName.lastIndexOf("\\") + 1, fileName.length());
                    System.out.println(fileName);

                    // 保存文件在服务器的物理磁盘中:第一个参数是:完整路径(不包括文件名)第二个参数是:文件名称
                    // item.write(file);
                    // 修改文件名和物料名一致,且强行修改了文件扩展名为gif
                    // item.write(new File(uploadPath, itemNo + ".gif"));
                    // 将文件保存到目录下,不修改文件名
                    item.write(new File(uploadPath, fileName));

                    // 将图片文件名写入打数据库
                    // itemManager.uploadItemImage(itemNo, fileName);

                }
            }
            //response.sendRedirect(request.getContextPath()
            //        + "/servlet/item/SearchItemServlet");
        } catch (Exception e) {
            e.printStackTrace();
            // throw new ApplicationException("上传失败!");
        }

    }

}

虚拟目录

用ecplise写好项目,export 导出成.war文件,然后 把该文件放入Tomcat(我的tomcat放在E:\service\Tomcat 7.0)的webapp目录中,运行tomcat会自动解压该文件,此时就可以运行该项目了。

配置虚拟目录:把解压得到的项目文件(我的是huaChen2)放入到其他的地方,比如E:\service\myproject,打开E:\service\Tomcat 7.0\conf中的server.xml文件,加入红色的部分。就ok了

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
               
        <Context path="/huaChen2" docBase="E:\service\myproject\huaChen2" debug="0" reloadable="true" crossContext="true"></Context>

      </Host>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值