IE上传文件到服务器

简介:

前言:项目用的是struts1,想要上传文件必须用jsp,传输指定类型写struts1标签,这样局限性太强,果断放弃,写一个servlet来实现。

web.xml

<servlet>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.phlx.product.wx.action.UploadServlet</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet.action</url-pattern>
  </servlet-mapping>

servlet

package ********;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.human.util.SysConst;
 

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
         response.setCharacterEncoding("utf-8");
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8"); 

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        //String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        
        // 获取配置文件中项目绝对路径,并截取到WebRoot\\
         String queryPath = SysConst.getConfField("queryPath");
         queryPath = queryPath.substring(0, queryPath.indexOf("WEB-INF"));
         // 获取上传的图片
         String uploadPath = "wxproduct\\img\\" + System.currentTimeMillis();
         String filedest = queryPath + uploadPath;
         System.out.println("filedest:" + filedest);
         
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        response.setCharacterEncoding("utf-8");
        Map<String, String> map = new HashMap<String, String>();
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filedest);
                        // 在控制台输出文件的上传路径
                        System.out.println(filedest);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message",
                            "文件上传成功!");
                        map.put("errcode", "0");
                        map.put("picUrl", uploadPath);
                        map.put("msg", "上传成功");
                    }
                }
            }
        } catch (Exception ex) {
            map.put("errcode", "-1");
            map.put("picUrl", "-1");
            map.put("msg", "上传失败");
        }
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();

        String json = gson.toJson(map);
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.write(json);
        out.flush();
        out.close();
        
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

这里主要说前台实现,用jquery实现ajax异步上传,上传没问题。
upload.html

<!DOCTYPE html>
<html>
<head>
    <title>消息查询</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <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="X-UA-Compatible" content="IE=8" >
    <script type="text/javascript" src="../../js/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="../../js/jquery.easyui.min1.4.4.js"></script>
    <script type="text/javascript" src="../../js/easyui-lang-zh_CN.js"></script>
</head>
<body>
<img style="display:none;" id="imgFile"/>
<input id="text" type="text" name="text"/>
    <form method="post" id="fm11" enctype="multipart/form-data" >
        <input name="uploadFile"  id="uploadFile" type="file" 
onchange="submitForm(this.value)" style="position:absolute;left:0;top:0;
width:100%;height:100%;z-index:999;opacity:0;filter:Alpha(Opacity=0)"/>
    </form>

</body>
<script type="text/javascript">
    function submitForm(tvalue){
        var aa = tvalue.split(".");
        if(aa[aa.length-1]=='gif'||aa[aa.length-1]=='jpg'||aa[aa.length-1]=='bmp'
            ||aa[aa.length-1]=='png'||aa[aa.length-1]=='jpeg'){
         $('#fm11').form('submit',{
                     url:"/WebRoot/UploadServlet.action",
                     onSubmit: function(){
                        return $(this).form('validate');
                    },
                    success: function(result){
                        var result = eval('('+result+')');
                        if (result.errcode=='0'){
                            $("#text").val(result.picUrl);
                            $("#imgFile").attr("src","/WebRoot/"+result.picUrl);
                            $("#imgFile").show();
                            //$("#uploadFile").val(result.picUrl);
                        } else {
                            alert("上传失败!");
                            /* $.messager.show({
                                title: '操作不成功!',
                                msg: result.msg
                            }); */
                        }
                    }
                }); 
        }else{
            alert("文件格式错误,请重新选择图片!");
            /* $.messager.alert({
                title: '文件格式错误',
                msg: '请选择图片!'
            }); */
        
        }
    }
</script>
</html>

但是现在的问题是,系统使用的是IE8,file标签的样式是不能修改的
现在有两种方式类实现:

1、将file隐藏,用其他案件来触发file的click事件,实现修改的目的,
但是,这种方式在ie上是不实现的,应为处于安全考虑,ie不允许代码实现触发上传功能,可以选择文件,提交显示,访问被拒绝,直接就是不走后台的。

2、把form放在a标签中,大小与a标签对齐,是file标签透明:opacity:0;
“opacity:0;”在ie8以下是不兼容的,所以得用filter:Alpha(Opacity=0)

最终代码如下:替换body中所有代码

<img style="display:none;" id="imgFile"/>
<input id="text" type="text" name="text"/>
<a style="position:relative;display:block;width:100px;height:30px;background:#EEE;border:1px solid #999;text-align:center;"  href="javascript:void(0);" >上传
<div style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:999;opacity:0;">
    <form method="post" id="fm11" enctype="multipart/form-data" >
        <input name="uploadFile"  id="uploadFile" type="file" onchange="submitForm(this.value)" style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:999;opacity:0;filter:Alpha(Opacity=0)"/>
    </form>
</div>
</a>
目录
相关文章
|
1月前
|
缓存 网络协议 数据可视化
WinSCP下载安装并实现远程SSH本地服务器上传文件
WinSCP下载安装并实现远程SSH本地服务器上传文件
|
3月前
Socket网络编程练习题三:客户端上传文件到服务器
Socket网络编程练习题三:客户端上传文件到服务器
|
6月前
|
存储 网络安全 数据安全/隐私保护
scp上传文件到远程服务器,如何避免每次都要输入远程服务器的密码
scp上传文件到远程服务器,如何避免每次都要输入远程服务器的密码
110 0
|
4月前
|
应用服务中间件 开发工具 Android开发
Tomcat配置虚拟路径,使上传文件与服务器分离
Tomcat配置虚拟路径,使上传文件与服务器分离
56 0
|
6月前
|
JSON C# 数据格式
.net core 上传文件到本地服务器
## 1、本文是上传文件到本地服务器,主要以作者做的业务上传apk为例子,下面直接上代码 ```csharp [HttpGet, HttpPost, HttpOptions] [Consumes("application/json", "multipart/form-data")] public IActionResult UploadFileToServer([FromForm] IFormCollection file) { try { IFormFile item = null; if(file.IsNull() || file.Count
60 0
|
7月前
|
Web App开发 前端开发 JavaScript
使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误试读版
使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误试读版
33 0
|
7月前
|
数据库
如何使用 SAP OData 服务向 ABAP 服务器上传文件试读版
如何使用 SAP OData 服务向 ABAP 服务器上传文件试读版
54 0
|
10月前
|
Java
向服务器端上传文件(Java代码)
向服务器端上传文件(Java代码)
229 0
|
10月前
|
Java Linux Shell
java上传文件到sftp服务器
最近公司有个数据对接需求,合作方那边是使用我们这边的系统进行出单的,数据首先也是在我们这边。后面他们自己开发了业务系统,需要我们这边定时把每天的数据传送到那边去。他们那边开发部门要求我们这边,按一定的格式导出加签加密的数据文件到他们的sftp服务器上面去。
193 0
|
11月前
|
XML Java Linux
centos7 配置 sftp 服务器并通过 java 上传文件
centos7 配置 sftp 服务器并通过 java 上传文件
317 0