SmartUpload实现图片上传&带预览功能

本文介绍了一种使用Java实现文件上传的方法,通过SmartUpload组件完成文件上传功能,并展示了如何预览上传的图片及处理上传过程中的各种参数设置。

1.页面设计

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
  <title>Smartupload</title>
  <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <style type="text/css">
      div{
          width: 400px;
          margin: auto;
          background-color: lightgoldenrodyellow;
      }

    label{
        width: 100px;
        display: inline-block;
        float: left;
    }
    #pic {
      width: 200px;
      height: 200px;
      margin: 20px auto;
      cursor: pointer;
    }
  </style>
</head>
<!-- 使用SmartUpload.jar 实现文件上传 -->
<body>
<h2 align="center">文件上传</h2>
<div>
<form action="smartUploadOne.do" method="post" enctype="multipart/form-data">
  <label>用户名:</label><input type="text" name="username" /><br><br>

  <label>上传文件1:</label><img id="pic" src="images/preview.jpg"> 
  <input id="upload" name="myfile1" accept="image/*" type="file" style="display: none" /><br><br> 
  <input type="submit" value="提交">
</form>
</div>
<script type="text/javascript">
    $(function() {
        $("#pic").click(function() {
            $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
            $("#upload").on("change", function() {
                var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
                if (objUrl) {
                    $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片
                }
            });
        });
    });


    //建立一個可存取到該file的url
    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
</script>
</body>

</html>

2.Servlet后台处理

package com.ambow.controller;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;


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 com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

@WebServlet("/smartUploadOne.do")
public class SmartUploadOne extends HttpServlet {


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

        //设置上传文件保存路径
        String filePath = getServletContext().getRealPath("/") + "images";
        System.out.println(filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }

        SmartUpload su = new SmartUpload();
        //初始化对象
        su.initialize(getServletConfig(), request, response);
        //设置上传文件大小
        su.setMaxFileSize(1024 * 1024 * 10);
        //设置所有文件的大小
        su.setTotalMaxFileSize(1024 * 1024 * 100);
        //设置允许上传文件类型
        su.setAllowedFilesList("txt,jpg,gif,png");
        String result = "上传成功!";
        //设置禁止上传的文件类型

        String username = "";
        String imageurl = "";
        try {
            su.setDeniedFilesList("rar,jsp,js");
            //上传文件
            su.upload();

            username = su.getRequest().getParameter("username");
            System.out.println(username);
            int count = su.save(filePath);
            System.out.println("上传成功" + count + "个文件!");
        } catch (Exception e) {
            result = "上传失败!";
            e.printStackTrace();
        }

        for (int i = 0; i < su.getFiles().getCount(); i++) {
            com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
            System.out.println("---------------------------");
            System.out.println("表单当中name属性值:" + tempFile.getFieldName());
            System.out.println("上传文件名:" + tempFile.getFieldName());
            System.out.println("上传文件长度:" + tempFile.getSize());
            System.out.println("上传文件的拓展名:" + tempFile.getFileExt());
            System.out.println("上传文件的全名:" + tempFile.getFilePathName());
            imageurl = tempFile.getFilePathName();
            System.out.println("---------------------------");
        }

        request.setAttribute("result", result);
        request.setAttribute("username",username);
        request.setAttribute("imageurl",imageurl);
        request.getRequestDispatcher("images.jsp").forward(request, response);
    }


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


}

3. 回显数据页面

<%--
  Created by IntelliJ IDEA.
  User: FoxBill
  Date: 2019/12/19 0019
  Time: 21:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>回显图片</title>
    <style type="text/css">
        div{
            width: 400px;
            margin: auto;
            background-color: bisque;
        }
    </style>
</head>
<body>
    <h1 align="center">${result}</h1>
    <div>
    <b>用户名:</b>${username}<br><br>
    <b>图片的路径为:</b>${pageContext.request.contextPath}/images/${imageurl}<br><br>
    <img src="${pageContext.request.contextPath}/images/${imageurl}" width="200" height="200">
    </div>
</body>
</html>

其中使用的jar包:jar包下载地址-解决中文乱码

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值