前端jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
<link href="js/b/css/bootstrap.min.css" rel="stylesheet">
<link href="js/b/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/theme.css" rel="stylesheet">
<script src="js/b/js/jquery-1.11.1.min.js"></script>
<script src="js/b/js/bootstrap.min.js"></script>
<script src="js/ajaxfileupload.js"></script>
<script src="js/index.js"></script>
</head>
<body >
<h2>表单提交的方式上传文件</h2>
<form method="post" action="file/upload.do" enctype="multipart/form-data">
file:<input type="file" name="file" id="file" /><br>
id:<input type="text" name="id" value="123" id="id" /><br>
<input type="submit" value="提交" />
</form>
<hr>
<h2>ajax文件上传方式</h2>
file:<input type="file" name="file1" id="file1" />
<input type="button" value="上传" id="btn01Id" />
</body>
</html>

前端js

/**
* 页面加载之后执行的函数;=====================================
*/
$(function() { }); /**
* 元素事件注册函数;=====================================
*/
$(function() {
$('#btn01Id').click(btn01IdClick);
});
/**
* 全局变量定义部分;=====================================
*/
var i = 0; /**
* 事件编写部分;=====================================
*/
function btn01IdClick(e) {
if(!$("#file1").val()){
return ;
}
var sendData = {
"id" : 123
};
$.ajaxFileUpload({
url:'file/upload.do',
secureuri:false,
fileElementId:'file1',
data : sendData,
timeOut : 5000,
success: function (data, status){
alert("上传成功!");
},
error: function (data, status, e){
alert("上传出错:"+e);
}
}); }

ajaxfileuploadjs

jQuery.extend({

    createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"'; }
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"'; }
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form); //set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status ); // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{ var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}}; }, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts(); return data;
}
})

后端controller

package com.srie.fileud.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/file")
public class FileUD {
@ResponseBody
@RequestMapping("/upload")
public String uploadFile(HttpServletRequest request, MultipartFile file1, Integer id) {
System.out.println("id is : "+id); String name = file1.getName();
System.out.println("name : "+name);
String contentType = file1.getContentType();
System.out.println("contentType : "+contentType);
String originalFilename = file1.getOriginalFilename();
System.out.println("originalFilename: "+originalFilename);
long size = file1.getSize();
System.out.println("size: "+size);
boolean empty = file1.isEmpty();
System.out.println("empty: "+empty); File saveFile = new File(request.getServletContext().getRealPath("/file"), originalFilename);
try {
file1.transferTo(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
return "asdf";
} @ResponseBody
@RequestMapping(value="/download")
public String downFile(HttpServletRequest request, HttpServletResponse response){
String directory = request.getServletContext().getRealPath("/file");
File file = new File(directory,"123");
if(file.exists()){
response.setContentType("application/octet-stream;charset=ISO8859-1");
String name = "《中文》09aa囿気.docx";
String name2 = "a.docx";
try {
name2 = new String(name.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.addHeader("content-disposition", "attachment;filename="+name2);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while(i!=-1){
os.write(buffer,0,i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bis!=null){
try {
bis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
} return null;
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>fileud</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.liveBeansView.mbeanDomain</param-name>
<param-value>dev</param-value>
</context-param>
</web-app>

springmvc.xml

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<!-- spring mvc 注解驱动 -->
<mvc:annotation-driven />
<!-- 扫描器 -->
<context:component-scan base-package="com.srie.fileud.controller" />
<!-- 配置视图 解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<!-- 前缀和后缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="200000" />
</bean>
<!-- 从请求和响应读取/编写字符串 -->
<bean id="stringHttpMessage" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 用于将对象转换为JSON -->
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessage" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
</beans>

spring mvc上传下载文件的更多相关文章

  1. Spring框架学习(8)spring mvc上传下载

    内容源自:spring mvc上传下载 如下示例: 页面: web.xml: <?xml version="1.0" encoding="UTF-8"?& ...

  2. asp.net mvc 上传下载文件的几种方式

    view: <!DOCTYPE html> <html> <head> <meta name="viewport" content=&qu ...

  3. Spring MVC上传文件原理和resolveLazily说明

    问题:使用Spring MVC上传大文件,发现从页面提交,到进入后台controller,时间很长.怀疑是文件上传完成后,才进入.由于在HTTP首部自定义了“Token”字段用于权限校验,Token的 ...

  4. Spring MVC上传文件

    Spring MVC上传文件 1.Web.xml中加入 <servlet> <servlet-name>springmvc</servlet-name> <s ...

  5. Spring MVC 上传文件

    Spring MVC上传文件需要如下步骤: 1.前台页面,form属性 method设置为post,enctype="multipart/form-data"  input的typ ...

  6. rz和sz上传下载文件工具lrzsz

    ######################### rz和sz上传下载文件工具lrzsz ####################################################### ...

  7. linux上很方便的上传下载文件工具rz和sz

    linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...

  8. shell通过ftp实现上传/下载文件

    直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...

  9. .Net mvc 上传多文件

    .net mvc 上传多文件有很多种方式,我的方法只是其中一种, 仅供参考,我主要是注重参数传递的过程,后面文件保存的地方省略.. 调试环境 vs2017 控制器代码: [HttpPost] publ ...

随机推荐

  1. FZU 2168 防守阵地 I(前n项和的前n项和)

    这是一道很容易超时的题,我超了n次了,后来队友提示我才想到,bigsum ! ! ! !就是前n项和的前n项和 #include<iostream> #include<cstdio& ...

  2. HDU 5531 Rebuild

    2015 ACM/ICPC 长春现场赛 E题 三分. 如果节点个数是奇数,那么直接列方程可以求解,因为,如果第一个圆半径变大,必然导致最后一个圆的半径变大, 所以,节点是奇数的时候,要么无解,要么只有 ...

  3. 运行时设计(Design at Run-time)

    1.定义 传统软件开发必须经历“设计时”和“运行时”两个阶段,运行时设计,顾名思义,就是在软件运行过程中,对软件进行实时设计修改,而无需再次进行编译,用户即可使用. “运行时设计(Design at ...

  4. Task 编程中的异常处理

    在 .Net 开发中, 使用 Task . Task<T> 进行异步编程是非常方便的, 但是在处理 Task 产生的异常时, 需要注意一个问题, 比如下面的代码: ? 1 2 3 4 5 ...

  5. vmware中的bridge、nat、host-only的区别

    概述: VMWare提供了三种工作模式,它们是bridged(桥接模式).NAT(网络地址转换模式)和host-only(主机模式).要想在网络管理和维护中合理应用它们,你就应该先了解一下这三种工作模 ...

  6. CodeForces 616D Longest k-Good Segment

    用队列维护一下即可 #include<cstdio> #include<cstring> #include<queue> #include<algorithm ...

  7. JS操作DOM对象——JS基础知识(四)

    一.JavaScript的三个重要组成部分 (1)ECMAScript(欧洲计算机制造商协会) 制定JS的规范 (2)DOM(文档对象模型)重点学习对象 处理网页内容的方法和接口 (3)BOM(浏览器 ...

  8. jquery如何判断元素是否被点击_百度知道

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <div id="parent"> <a id="a1" ...

  9. POJ 3494 Largest Submatrix of All 1’s

    POJ 2796 Feel Good HDU 1506 Largest Rectangle in a Histogram 和这两题一样的方法. #include<cstdio> #incl ...

  10. protobuf c++ API

    1.在.proto文件中定义消息格式 2.使用protobuf编译器 3.使用c++ api来读写消息   0.为何使用protobuf?   1.原始内存数据结构,可以以二进制方式sent/save ...