文件上传到服务器的2种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengTornado/article/details/52278865

方法一SmartUpload对象上传

用到jsmartcom_zh_CN.jar包

//用smartupload方法上传

package com.ruide.action;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class UploadSmart1Action extends HttpServlet {

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

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        SmartUpload smart=new SmartUpload();
        smart.initialize(this.getServletConfig(),request, response);
        smart.setMaxFileSize(1024*1024*1024);
        try {
            smart.setDeniedFilesList("exe,bat,,");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            smart.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        Files fs=smart.getFiles();////是个文件集合,得到所有文件
        File f=fs.getFile(0);
        String filename=f.getFileName();//原文件名
        long times=System.currentTimeMillis();//系统当前时间
        String newfilename=times+filename.substring(filename.indexOf("."));//系统当前时间+截取源文件名后获取后缀名
        //System.out.println(newfilename);
        //获取当前工程的路径名,加上新的文件名
        String path=request.getRealPath("/files/");
        path=path+"\\"+newfilename;
        //保存文件
        try {
            f.saveAs(path);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

    }

}

下面是jsp页面的测试

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'upload.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <form action="uploadsmart1" method="post" enctype="multipart/form-data">
    <p>用户名:<input type="text" name="username" /></p>
    <p>用户密码:<input type="password" name="userpass" /></p>
    <p>上传照片:<input type="file" name="photo"  value="浏览"/></p>
    <p><input type="submit" value="提交"></p>
    </form>
  </body>
</html>

方法二ServletFileUpload对象上传,支持多文件上传

用到两个jar包:commons-fileupload-1.2.1.jar和commons-io-1.4.jar

package com.ruide.action;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CommonFileUpload1Action extends HttpServlet {

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

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> list=upload.parseRequest(request);
            for(int i=0;i<list.size();i++){
                FileItem fi=list.get(i);
                boolean iden=fi.isFormField();
                if(iden){//处理普通文件
                    String name=fi.getFieldName();

                    String value=fi.getString("GBK");
                }else{//处理文件
                    //文件的文件名
                    String name=fi.getName();////有的电脑得到的是文件名,有的电脑得到的是路径+文件名
                    name=name.substring(name.lastIndexOf("\\")+1);//处理出现第二种“路径+文件名”做到各个电脑或浏览器都兼容该上传方式
                    long times=System.currentTimeMillis();
                    String newname=times+name.substring(name.lastIndexOf("."));//时间+后缀的文件
                    String path=request.getRealPath("/files/");
                    File f=new File(path+"/"+newname);  
                    fi.write(f);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

下面是jsp页面的测试代码

 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'uploadapache.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
        function doadd(){
            var tb=document.getElementById("tb");
            var tr=document.createElement("tr");
            var td=document.createElement("td");
            var f=document.createElement("input");
            f.name="filename";
            f.type="file";
            var btn=document.createElement("input");
            btn.type="button";
            btn.value="delete";
            btn.onclick=function(){
                tb.removeChild(tr);
            }
            td.appendChild(f);
            td.appendChild(btn);
            tr.appendChild(td);
            tb.appendChild(tr);
        }
    </script>
  </head>

  <body>
    <form action="commonfileupload1" method="post" enctype="multipart/form-data">
        <p>用户名:<input type="text" name="username" /></p>
        <p>用户密码:<input type="password" name="userpass" /></p>
        <p>上传照片:<input type="file" name="photo" value="浏览"/>
            <input type="button" onclick="doadd()" value="创建" />
        </p>
        <table border="0">
            <tbody id="tb">

            </tbody>
        </table>
        <p><input type="submit" value="提交" /></p>   
    </form>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/zhengTornado/article/details/52278865