java 实现文件(照片)上传和下载,并回显

1、控制层:

package com.santi.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.santi.constant.RedisConstant;
import com.santi.mapper.FilesMapper;
import com.santi.pojo.Files;
import com.santi.result.ResultMsg;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FilesMapper filesMapper;

    /***
     * 文件重命名以后,名称不一致了,显示给用户,用户就分布清楚具体文件是做什么的.
     *
     * **/
    @PostMapping("/upload")
    public ModelAndView upload(@Param("file") MultipartFile file, ModelAndView mv) {
        String orgName = file.getOriginalFilename();
        String suf = orgName.substring(orgName.lastIndexOf(".") + 1);
        try {
            InputStream is = file.getInputStream();
            //通过流写到对应的目录
            //20220921
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String day = sdf.format(new Date());
            // /day/自定义文件名
            String uid = UUID.randomUUID().toString().replace("-", "");
            String path = File.separator + day + File.separator + uid + "." + suf;

            File f = new File(RedisConstant.IMAGE_PTAH, path);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            file.transferTo(f);

            Files files = new Files();
            files.setFileLocalName(orgName);
            files.setFileServiceName(uid + "." + suf);
            files.setFilePath(path);

            //保存文件信息
            filesMapper.uploadPhoto(files);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mv.setViewName("redirect:http://127.0.0.1:8848/TestHtml/res/test.html");
        return mv;
    }


    @RequestMapping("/list")
    public ResultMsg list() {
        List<Files> list = filesMapper.queryAll();

        for (Files file : list) {
            //http://localhost:8888/spring-book/file/download
            String baseUrl="http://localhost:8080/OrderTest";
            file.setFilePath(baseUrl + "/file/download?id=" + file.getFileId());
        }


//        //通过ajax将数据返回前端
//        ResultMsg rm = new ResultMessage();
//        rm.setCode(200);
//        rm.setMsg("成功");
//        rm.setData(list);

        return ResultMsg.ok(list);
    }

    @GetMapping("/download")
    public void download(Integer id, HttpServletResponse response) {
        //查询数据库找到文件数据
        Files files = filesMapper.queryById(id);

        //进行下载逻辑
        File localFile = new File(RedisConstant.IMAGE_PTAH, files.getFilePath());
        if (localFile.exists()) {
            //進行下載
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(files.getFileLocalName().getBytes()));
            response.addHeader("Content-Length", "" + localFile.length());
            response.setContentType("application/octet-stream");

            try {
                IOUtils.copy(new FileInputStream(localFile), response.getOutputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

2、实体类

package com.santi.pojo;

/**
 * 图片上传类
 */
public class Files {

    private Integer fileId;
    private String fileServiceName;
    private String fileLocalName;
    private String filePath;

    get和set方法、构造函数、toString
}

3、所用jar

<spring.version>5.3.1</spring.version>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--spring整合junit-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--mybatis包-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <!--spring整合mybatis包-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <!--数据源-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.9</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <!--日志-->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.2</version>
    </dependency>
    <!--测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!--mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!--分页包-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.2.0</version>
    </dependency>
    <!--前端控制器需要DispatcherServlet-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <!--json数据-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.2</version>
            </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>2.0.10</version>
    </dependency>
    <!--文件上传包-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <!--redis-->

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
    </dependency>
    <!-- spring 操作redis的包 -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.3</version>
    </dependency>
</dependencies>

4、前端代码 test.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="./js/jquery-1.8.3.js"></script>
        <script>
            $.ajax({
                url: "http://localhost:8080/OrderTest/file/list",
                type: "POST",
                dataType: "json",
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json;charset=UTF-8',
                },
                success: function(resp) {

                    var data = resp.data;

                    var len = data.length;
                    var html = "";
                    for (var i = 0; i < len; i++) {
                        var item = data[i];
                        html += "<a href='" + item.filePath + "'>" + item.fileLocalName + "</a><br/><img src='"+item.filePath+"'/>;"
                        
                    }
                    $("#content").html(html);
                }
            });
        </script>
    </head>
    <body>
        <div id="content"></div>
    </body>
</html>

upload.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>文件上传功能</title>
        <script type="text/javascript" src="../static/script/jquery-1.7.2.js"></script>

    </head>
    <body>
        <pre>
    1.文件上传,上传的不是用户本地的路径,而是当做一个流进行数据传输
    2.上传文件,不要将代码和资源文件放在一起。如果有多个项目,同时共享公司的资源文件,那么放到项目中,就不合理了.
    3.约定好上传文件的根目录.(意思就是所有的项目都放置到那个目录,且保存的是个相对根目录的相对路径)
</pre>
        <div>文件列表</div>
        <!-- 显示上传了的文件 -->
        <!--  <div id="filelist">


    </div> -->

        <!-- 同步上传表单,只有进行文件上传才会使用 -->
        <!--
        input-type : submit  -> 点击后提交的是form表单的配置
        input-type : button  -> 它就是一个按钮,点击没有任何效果,如果需要相关功能,需要绑定相关事件进行执行js方法
    -->
        <form id="myFileForm" action="http://localhost:8080/OrderTest/file/upload" method="post"
            enctype="multipart/form-data">
            <input name="file" type="file" value="文件上传">
            <input type="submit" value="确定">
        </form>

    </body>
</html>

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现JSP和Servlet上传多个文件回显,可以参考以下步骤: 1. 在JSP页面中添加一个表单,包含一个文件上传输入框和一个提交按钮。 ```html <form action="uploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="上传" /> </form> ``` 2. 在Servlet中处理文件上传逻辑,将上传文件保存到服务器的指定目录中。 ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上传文件的集合 List<Part> parts = (List<Part>) request.getParts(); // 遍历所有上传文件 for (Part part : parts) { // 获取上传文件文件名 String fileName = part.getSubmittedFileName(); // 将上传文件保存到服务器指定目录 part.write("D:\\" + fileName); } // 回显上传成功信息 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<h3>文件上传成功!</h3>"); } ``` 3. 在JSP页面中显示上传成功信息和上传文件列表。 ```html <%-- 显示上传成功信息 --%> <% if (request.getParameter("message") != null) { %> <div class="message"><%= request.getParameter("message") %></div> <% } %> <%-- 显示上传文件列表 --%> <% File uploadDir = new File("D:\\"); %> <% if (uploadDir.exists()) { %> <ul class="file-list"> <% for (File file : uploadDir.listFiles()) { %> <li><%= file.getName() %></li> <% } %> </ul> <% } %> ``` 4. 在CSS文件中定义样式。 ```css .message { color: green; font-weight: bold; } .file-list { list-style: none; margin: 0; padding: 0; } .file-list li { margin: 5px 0; padding: 5px; background-color: #EEE; } ``` 这样就可以实现JSP和Servlet上传多个文件回显的功能了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小朱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值