在前端页面上传文件到服务器方法示例

在前端页面上传文件到服务器方法示例

1.选择图片

 <div class="item1 update_pic" >
     <span>摘要图片:</span>
     <img src="${pageContext.request.contextPath}/upload/<s:property value="article_pic" />" id="imageview" class="item1_img" >
     <label for="fileupload" id="label_file">上传文件</label>
     <input type="file" name="upload" id="fileupload"/>
</div>
 /*原理是把本地图片路径:"D(盘符):/image/..."转为"http://..."格式路径来进行显示图片*/
    $("#fileupload").change(function() {
        var $file = $(this);
        var objUrl = $file[0].files[0];
        //获得一个http格式的url路径:mozilla(firefox)||webkit or chrome
        var windowURL = window.URL || window.webkitURL;
        //createObjectURL创建一个指向该参数对象(图片)的URL
        var dataURL;
        dataURL = windowURL.createObjectURL(objUrl);
        $("#imageview").attr("src",dataURL);
        console.log($('#imageview').attr('style'));
        if($('#imageview').attr('style') === 'display: none;'){
            $('#imageview').attr('style','inline');
            $('#imageview').width("300px");
            $('#imageview').height("200px");
            $('.update_pic').attr('style', 'margin-bottom: 80px;');
        }
    });

2.上传图片

       1).form表单enctype设置为multipart/form-data.

<!--在from中添加的属性enctype="multipart/form-data"-->
<form id="blog_form" action="${ctx}/article_update.action" method=post enctype="multipart/form-data">
        <div class="edit_content">
            <div class="item1">
                <div>
                    <span>文章标题:</span>
                    <input type="text" class="am-form-field" name="article_title" style="width: 300px"
                    value="<s:property value="article_title" />"
                    >&nbsp;&nbsp;
                </div>
            </div>

            <input type="text" name="article_desc" id="article_desc" style="display: none;">


            <div class="item1">
                <span>所属分类:</span>
                <select id="category_select" name="category.parentid" style="width: 150px">&nbsp;&nbsp;
                     
                </select>

                <select id="skill_select" name="category.cid" style="width: 150px">&nbsp;&nbsp;

                </select>

            </div>

            <div class="item1 update_pic" >
                <span>摘要图片:</span>
                <img src="${pageContext.request.contextPath}/upload/<s:property value="article_pic" />" id="imageview" class="item1_img" >
                <label for="fileupload" id="label_file">上传文件</label>
                <input type="file" name="upload" id="fileupload"/>
            </div>

            <div id="editor" name="article_content" style="width:900px;height:400px;"></div>
            <input type="hidden" id="resContent" value="<s:property value="article_content"/>">
            <input type="hidden" name="article_id" value="<s:property value="article_id"/>">
            <input type="hidden" name="article_pic" value="<s:property value="article_pic"/>">
            <button class="am-btn am-btn-default" type="button" id="send" style="margin-top: 10px;">
                修改</button>
        </div>

    </form>

        2).服务器提供属性接收

        3).上传文件处理

    /**
     * 文件上传提供的三个属性:
     */
    @Setter
    private String uploadFileName; // 文件名称
    @Setter
    private File upload; // 上传文件(文件路径)
    @Setter
    private String uploadContentType; // 文件类型
    public String add() throws IOException {
        System.out.println("add-web层");
        //上传图片
        if(upload != null){
            //上传文件
            //随机生成文件名称
            //1.获取文件的扩展名
            int index = uploadFileName.lastIndexOf(".");
            String etx = uploadFileName.substring(index);
            //2.随机生成文件名 拼接扩展名
            String uuid = UUID.randomUUID().toString();/*生成的文件名是带“-”的,所以要去掉*/
            String uuidFileName = uuid.replace("-", "") + etx;
            //确定上传的路径
            String path = ServletActionContext.getServletContext().getRealPath("/upload");
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            //拼接新的文件路径
            File desFile = new File(path + "/" + uuidFileName);
            //文件上传
            FileUtils.copyFile(upload,desFile);

            //设置图片
            article.setArticle_pic(uuidFileName);
        }
       //设置当前时间
        article.setArticle_time(new Date().getTime());
        System.out.println(article);
        //调用业务层保存到数据库当中
        articleService.save(article);
        return "listres";
    }

3.集成富文本编辑器

umedit下载地址
               https://ueditor.baidu.com/website/download.html
       添加到页面添加
               1).引入js
                    <script type="text/javascript" charset="utf-8" src="${ctx }/js/umedit/ueditor.config.js"></script>
                    <script type="text/javascript" charset="utf-8" src="${ctx }/js/umedit/ueditor.all.min.js"> </script>
                    <script type="text/javascript" charset="utf-8" src="${ctx }/js/umedit/lang/zh-cn/zh-cn.js"></script>
               2).在页面当中提供div标签供显示内容
                    <div id="editor" name="article_content" style="width:900px;height:400px;"></div>
               3).在js当中初始化富文本编辑器
                    var ue = UE.getEditor('editor');

4.富文本编辑器文件上传

            1).添加uedit相关jar包

            2).配置过滤器

package com.helong.web.filter;

import org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter extends StrutsPrepareAndExecuteFilter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //获取当前请求
        HttpServletRequest request = (HttpServletRequest) req;
        //获取请求的地址来进行判断
        String requestURI = request.getRequestURI();
        if(requestURI.contains("js/umedit/jsp/controller.jsp")){
            //放行
            chain.doFilter(req,res);
        }else{
            super.doFilter(req,res,chain);
        }
    }

}

            3).json文件配置获取图片路径

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    /* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "http://localhost:8080/", /* 图片访问路径前缀 */
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用以下代码在前端使用JavaScript上传文件服务器: ```javascript // 获取 input[type="file"] 元素 const input = document.querySelector('input[type="file"]'); // 监听 input[type="file"] 元素的 change 事件 input.addEventListener('change', () => { // 创建 FormData 对象 const formData = new FormData(); // 将文件添加到 FormData 对象中 const file = input.files[0]; formData.append('file', file); // 发送 POST 请求到服务器 fetch('/upload', { method: 'POST', body: formData }) .then(response => { console.log('上传成功!'); }) .catch(error => { console.error('上传失败:', error); }); }); ``` 以上代码中,首先获取 input[type="file"] 元素,并监听其 change 事件。在事件处理程序中,创建 FormData 对象,并将文件添加到 FormData 对象中。然后使用 fetch 函数发送 POST 请求到服务器,并将 FormData 对象作为请求体发送。最后在 then 方法中处理上传成功的情况,在 catch 方法中处理上传失败的情况。 ### 回答2: 对于前端上传文件服务器的代码,用JavaScript实现通常需要以下步骤: 1. 首先,需要在HTML页面上创建一个文件选择的input元素,以便用户选择要上传的文件。例如: ```html <input type="file" id="fileInput"> ``` 2. 在JavaScript代码中,获取到file input的元素,并添加一个事件监听器以便在用户选择文件后执行上传操作。例如: ```javascript const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', handleFileUpload); ``` 3. 在事件处理函数中,获取用户选择的文件,然后使用FormData对象创建一个表单数据,以便将文件数据传递给服务器。例如: ```javascript function handleFileUpload(event) { const file = event.target.files[0]; const formData = new FormData(); formData.append('file', file); // 进行上传操作 uploadFile(formData); } ``` 4. 最后,使用XMLHttpRequest或fetch API发送文件上传请求到服务器。例如: ```javascript function uploadFile(formData) { const xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.send(formData); xhr.onload = function() { if (xhr.status === 200) { console.log('文件上传成功'); } else { console.error('文件上传失败'); } }; } ``` 在上述代码中,`/upload`是服务器端接收文件上传请求的URL,可以根据具体的后端实现进行修改。 以上是一个基本的前端上传文件服务器的代码实现。当用户选择文件并点击上传按钮时,会将文件数据发送给服务器端,并在上传成功或失败时给予相应提示。 ### 回答3: 下面是一个使用 JavaScript 编写的前端上传文件服务器的代码示例: 首先,需要在 HTML 页面中创建一个文件上传的表单,可以使用<input type="file">元素来实现: ```html <form id="uploadForm"> <input type="file" id="fileInput"> <button type="button" onclick="uploadFile()">上传</button> </form> ``` 然后,我们需要编写 JavaScript 函数来处理文件上传操作。在这个函数中,我们需要获取用户选择的文件,并使用AJAX将文件发送到服务器: ```javascript function uploadFile() { let fileInput = document.getElementById('fileInput'); let file = fileInput.files[0]; // 获取选中的文件 let formData = new FormData(); // 创建一个FormData对象 formData.append('file', file); // 将文件添加到FormData对象中 let xhr = new XMLHttpRequest(); // 创建一个XMLHttpRequest对象 xhr.open('POST', '/upload', true); // 设置请求的方法和URL xhr.onload = function() { if (xhr.status === 200) { console.log('文件上传成功'); } else { console.log('文件上传失败'); } }; xhr.send(formData); // 发送FormData对象到服务器 } ``` 在服务器端,你需要提供一个接收文件的路由。这个路由可以是一个后端接口(如使用Node.js + Express),或者一个框架自带的处理文件上传的路由(如Django中的`<form>`表单)。 以上是一个使用 JavaScript 编写的前端上传文件服务器的代码。你可以根据自己的需求对其进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值