Maven环境下的SSM框架实现上传与下载

0.maven环境的搭建及集成SSM框架:

https://blog.csdn.net/qq_37067955/article/details/83899758

1.准备工作

在项目中建立一个文件夹,用来存储上传的文件,一般存放的在项目静态文件的根目录下

2.配置pom.xml文件

在pom.xml文件中添加如下代码:

<!-- 文件上传下载 -->
		<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

3.配置applicationContext.xml文件

在applicationContext.xml文件中添加如下代码:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
	     <property name="defaultEncoding" value="utf-8"></property>    
	     <property name="maxUploadSize" value="5242440"></property>    <!--设置最大支持的上传文件大小 B-->
	</bean>

4.编写前台html文件

1.同步提交方式

#index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">
<title>文件上传下载</title>
</head>
<body>
    <form action="${pageContext.request.contextPath }/file/upload.action" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file" width="120px" accept=".docx">  <!-- accept用来控制上传的文件类型,可以为.docx/.pdf/.doc/.jpg…… -->
        <input type="submit" value="上传">
    </form>
    <form action="${pageContext.request.contextPath }/file/down.action" method="get">
        <input type="submit" value="下载">
    </form>
</body>
</html>
2 异步ajax提交方式:

#index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<html>  
  <head>  
    <base href="<%=basePath%>">  
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>  
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-form.js"></script>   
    <title>My JSP 'index.jsp' starting page</title>  
	<script type="text/javascript">
		$(function(){
			$("#submit").click(function(){
				var file = $('#indicatorAddExcelForm')[0];
				var formData = new FormData(file);
				alert(formData)
				$.ajax({
					type:"post",
					url:"/Test/upload.action",
					data: formData,
					cache: false,//文件不设置缓存
		            processData: false,//数据不被转换为字符串
		            contentType: false,//上传文件时使用,避免 JQuery 对其操作
					success:function(da){
						alert(da);
					}
				}) 
			})
		})
	</script>
  </head>  
    
  <body>  
    <form id="indicatorAddExcelForm"  enctype="multipart/form-data">         
		<input type="file" class="easyui-validatebox" id="file" name="file"> 
		<input type="button"  id="submit">      
       </form>  
  </body>  

5.编写后台逻辑控制页面

#FileController.java

1 同步提交
package com.ws.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
 * Maven环境下SSM框架实现上传与下载
 * @author 文升
 *
 */
@Controller
@RequestMapping("file")
public class FileController {
	
    @RequestMapping(value="upload",method=RequestMethod.POST)
    @ResponseBody  
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{  
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();    
        File dir = new File(path,fileName);          
        if(!dir.exists()){  
            dir.mkdirs();  
        }  
       
        file.transferTo(dir);  
        return fileName;  
    }  
    
       @RequestMapping("down")  
        public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{  
           
            String fileName = request.getSession().getServletContext().getRealPath("upload")+"/下载.docx";  
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
            String filename = "下载.docx";  
            filename = URLEncoder.encode(filename,"UTF-8");  
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);      
            response.setContentType("multipart/form-data");   
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
            int len = 0;  
            while((len = bis.read()) != -1){  
                out.write(len);  
                out.flush();  
            }  
            out.close();  
        }  
}
2 ajax异步提交
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.neu.util.ReadExcel;

@Controller
@RequestMapping("Test")
public class TextController {
	
	@RequestMapping(value="upload",method=RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{  
		String path = request.getSession().getServletContext().getRealPath("upload");
		
        String fileName = file.getOriginalFilename();    
        File dir = new File(path,fileName);          
        if(!dir.exists()){  
            dir.mkdirs();  
        }  

        file.transferTo(dir);
        
        ReadExcel readExcel = new ReadExcel();
			try {
				System.out.println(path+"\\"+fileName);
				readExcel.excel(path+"\\"+fileName);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        return fileName;  
    }
 }
源码分享
链接:https://pan.baidu.com/s/1QaMk-_gGiYvuuVLJ672AmQ 
提取码:5fw7 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DYS_房东的猫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值