SpringMVC文件上传,下载

SpringMVC的文件上传:

SpringMVC为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的。

1.导入依赖

添加文件上传相关依赖
      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
      </dependency>

2.springMVC-servlet的配置: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <context:component-scan base-package="com.zking.ssm"/>

    <!--开启MVC注解-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver  视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

  

    <!--配置文件上传解析器(CommonsMultipartResolver)-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>


    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <mvc:resources location="/images/" mapping="/images/**"/>
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
</beans>

3.web.xml配置

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>


  <!-- Spring和web项目集成start -->
  <!-- spring上下文配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring和web项目集成end -->

  <!-- 防止Spring内存溢出监听器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
 

  <!-- 中文乱码处理 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

4.BookMapper.xml上传方法:

<update id="uploadPath" parameterType="com.zking.ssm.model.Book">
  update t_mvc_book
  set filename = #{filename,jdbcType=VARCHAR}
  where bid = #{bid,jdbcType=VARCHAR}
</update>

5.controller配置:

package com.spring.ssm.controller;

import com.spring.ssm.model.Book;
import com.spring.ssm.service.BookService;
import com.spring.ssm.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * @author cst
 * @site www.xiaomage.com
 * @company xxx公司
 * @create 2018-12-21 17:04
 */

@Controller
@RequestMapping("/book")
public class BookController {

    private String servicePath="/imgs/";

    private String localPath="C:/Users/2018121005/Pictures/Camera Roll/";

    @Autowired
    private BookService bookService;

//上传方法
     @RequestMapping("/toUpload/{bid}")
    public String uploadPath(HttpServletRequest request,@PathVariable(value = "bid") String bid){
        Book book1 = bookService.selectByPrimaryKey(bid);
        request.setAttribute("book",book1);
        return "upload";
    }

    @RequestMapping("/upload/{bid}")
    public String uploadPath(MultipartFile file, HttpServletRequest request, Book book,@PathVariable(value = "bid") String bid){
        //得到上传的文件名
        String fileName=file.getOriginalFilename();
        String realPath=request.getServletContext().getRealPath(servicePath+fileName);
        System.out.println(realPath);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(realPath));
            book.setFilename(fileName);
            int i = this.bookService.uploadPath(book);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/book/list";
    }

//下载方法
     @RequestMapping("/downLoad")
    public String downLoad(String file, HttpServletResponse response, HttpServletRequest request){
        response.setContentType("image/jpg");
        response.setHeader("Content-Disposition","attachment;filename="+file);
        try {
            String realPath=request.getServletContext().getRealPath(servicePath+file);
            FileUtils.copyFile(new File(realPath),response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}

6.JSP页面:

bookList.jsp  展示页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     <%@ taglib uri="/zking" prefix="z" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="from" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<script type="text/javascript">
        function add(){
            window.location.href="${pageContext.request.contextPath}/book/toAdd";
        }

        function update(bid){
            window.location.href = "${pageContext.request.contextPath}/book/toUpdate/"+bid;
        }

        function del(bid){
            window.location.href = "${pageContext.request.contextPath}/book/delete/"+bid;
        }

        function uploadPath(bid) {
            window.location.href = "${pageContext.request.contextPath}/book/toUpload/"+bid;
        }

        function downLoad(filename) {
            window.location.href = "${pageContext.request.contextPath}/book/downLoad/"+filename;
        }


	</script>
	<title>Insert title here</title>
</head>
<body>

	<form action="${pageContext.request.contextPath}/book/list"
		method="post">
		书名:<input type="text" name="bname"> <input type="submit"
			value="确定">
	</form>
	<button onclick="add();">新增</button>
	<table border="1" width="100%">
		<tr>
			<td>编号</td>
			<td>名称</td>
			<td>价格</td>
			<td>图片</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${bookList }" var="b">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
				<td><img src="${pageContext.request.contextPath}/book/opAs?file=${b.filename}" style="width: 30px;height: 30px" ></td>
				<td>
					<button onclick="update(${b.bid });">修改</button>&nbsp;&nbsp;&nbsp;
					<button onclick="del(${b.bid });">删除</button>&nbsp;&nbsp;&nbsp;

					<button onclick="uploadPath(${b.bid });">上传</button>&nbsp;&nbsp;&nbsp;

					<a href="${pageContext.request.contextPath}/book/downLoad?file=${b.filename}">下载</a>

					
				</td>
			</tr>
		</c:forEach>
	</table>
	<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

upload.jsp  下载页面

<%--
  Created by IntelliJ IDEA.
  User: 2018121005
  Date: 2018/12/25
  Time: 19:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script type="text/javascript">
        function doSubmit(bid){
            var bookForm = document.getElementById("bookForm");
            if(bid){
                bookForm.action = '${pageContext.request.contextPath}/book/upload/'+bid;
            }
            bookForm.submit();
        }
    </script>

</head>
<body>

<form id="bookForm" method="post" action="" enctype="multipart/form-data">
    <input type="file" name="file">     <!--name="file" 要跟后台方法参数 MultipartFile file 一致-->
    <input type="submit" value="ok" onclick="doSubmit('${book.bid}');">
</form>

</body>
</html>

页面信息

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
图像识别技术在病虫害检测中的应用是一个快速发展的领域,它结合了计算机视觉和机器学习算法来自动识别和分类植物上的病虫害。以下是这一技术的一些关键步骤和组成部分: 1. **数据收集**:首先需要收集大量的植物图像数据,这些数据包括健康植物的图像以及受不同病虫害影响的植物图像。 2. **图像预处理**:对收集到的图像进行处理,以提高后续分析的准确性。这可能包括调整亮度、对比度、去噪、裁剪、缩放等。 3. **特征提取**:从图像中提取有助于识别病虫害的特征。这些特征可能包括颜色、纹理、形状、边缘等。 4. **模型训练**:使用机器学习算法(如支持向量机、随机森林、卷积神经网络等)来训练模型。训练过程中,算法会学习如何根据提取的特征来识别不同的病虫害。 5. **模型验证和测试**:在独立的测试集上验证模型的性能,以确保其准确性和泛化能力。 6. **部署和应用**:将训练好的模型部署到实际的病虫害检测系统中,可以是移动应用、网页服务或集成到智能农业设备中。 7. **实时监测**:在实际应用中,系统可以实时接收植物图像,并快速给出病虫害的检测结果。 8. **持续学习**:随着时间的推移,系统可以不断学习新的病虫害样本,以提高其识别能力。 9. **用户界面**:为了方便用户使用,通常会有一个用户友好的界面,显示检测结果,并提供进一步的指导或建议。 这项技术的优势在于它可以快速、准确地识别出病虫害,甚至在早期阶段就能发现问题,从而及时采取措施。此外,它还可以减少对化学农药的依赖,支持可持续农业发展。随着技术的不断进步,图像识别在病虫害检测中的应用将越来越广泛。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值