1.前端页面,通过form表单提交,必须设置

enctype="multipart/form-data"  代表form表单在发送到服务器时候编码方式是二进制类型,一般用于图片、mp3、文件
<form method="get" action="" class="form-horizontal" role="form" id="form_data" onsubmit="return check_form()" style="margin: 20px;" enctype="multipart/form-data">
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">配置信息</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="projectid" class="col-sm-3 control-label">项目名称</label>
<div class="col-sm-9">
<select class="form-control" name="projectid" id="projectid">
<c:forEach var="p" items="${projects }">
<option value="${p.projectid}">${p.projectname}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="apppackage" class="col-sm-3 control-label">app包名</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="apppackage" id="apppackage" placeholder="app包名">
</div>
</div> <div class="form-group">
<%--@declare id="files"--%>
<label for="files" class="col-sm-3 control-label">上传apk</label>
<div class="col-sm-9">
<input type="file" class="form-control" id="apkupload" name="files">
</div>
</div> <div class="form-group">
<label for="remark" class="col-sm-3 control-label">备注</label>
<div class="col-sm-9">
<textarea class="form-control" name="remark" id="remark" placeholder="备注"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="close">关闭</button>
<button type="submit" class="btn btn-primary" disabled="disabled">提交</button>
&nbsp;&nbsp;&nbsp;&nbsp;<span id="tip"> </span>
</div>
</div>
</div>
</div>
</form>

2. ajax请求

注意:contentType要设置为false,
当在form 标签中设置了enctype = “multipart/form-data”后,请求中的 contentType 会默认为 multipart/form-data 。
而ajax中contentType设置为false是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件(文件是需要分隔符的,比如文件内容和文本内容之间就是用分割符分割)
补充:
async 默认是true,即为异步方式,$.Ajax执行后,会继续执行ajax后面的脚本,直到服务器端返回数据后,触发$.Ajax里的success方法,这时候执行的是两个线程。
      若为false,则所有的请求均为同步请求,用户必须等待请求完成才能执行其他操作。
// 提交表单
function check_form(){
// var form_data = $('#form_data').serialize();
var formData = new FormData($( "#form_data" )[0]);
// 异步提交数据到action页面
$.ajax({
url: "configadd.do",
data:formData,
type: "post",
// dataType : "json",//返回数据的类型
async: false,
cache: false,
contentType: false,//发送数据的类型
processData: false,
beforeSend:function(){
$("#tip").html("<span style='color:blue'>正在处理...</span>");
return true;
},
success:function(data, status){
console.log("请求成功返回数据============="+status);
if(status == "success"){
alert("添加成功-------")
$("#tip").html("<span style='color:blueviolet'>恭喜,添加配置成功!</span>");
setTimeout(fn, 1000);
function fn(){
document.getElementById("close").click();
}
toastr.success(data.ms);
}else{
$("#tip").html("<span style='color:red'>失败,请重试</span>");
toastr.info(data.ms);
}
},
error:function(){
toastr.error('请求出错!');
},
complete:function(){
$('#addModal').hide();
}
});
return false;
}
3.Spring配置文件applicationContext.xml   中增加上传文件的配置
    <!--文件上传使用, 配置multipartResolver,id名为约定好的 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb -->
<property name="maxUploadSize" value="102400000" />
</bean>
<!--PropertiesFactoryBean对properties文件可用 ,可以用来注入properties配置文件的信息 -->
<bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:upload.properties"></property>
</bean>

4.文件上传的工具类

(一)上传到服务器

@Component(value="fileUploadUtils")
public class FileUploadUtil {
@Value("#{uploadProperties.path}")
private String path;
private String getExtName(MultipartFile file){
return FilenameUtils.getExtension(file.getOriginalFilename());
}
private String createNewName(MultipartFile file){
return UUID.randomUUID().toString()+"."+getExtName(file);
}
public String uploadFile(MultipartFile file){
try {
String newName=createNewName(file);
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName ));
return newName;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

(二)通过ftp远程上传

public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切换到上传目录
if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上传文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
} /**
* Description: 从FTP服务器下载文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
} ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
public static void main(String[] args) {
try {
FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));
boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

5.实体AppiumConfig中增加文件类型的属性

    private MultipartFile[] files;

6.控制层controller中,实现上传功能,保存上传文件的路径到实体

                    MultipartFile[] files = AppiumConfig.getFiles();
// System.out.println("真实路径:" + application.getRealPath("/"));
String path =application.getRealPath("/");
for (MultipartFile multipartFile : files) {
// System.out.println("文件类型:" + multipartFile.getContentType());
// System.out.println("文件控件名:" + multipartFile.getName());
// System.out.println("文件名:" + multipartFile.getOriginalFilename());
// System.out.println("文件大小:" + multipartFile.getSize());
try {
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(application.getRealPath("/") + "upload/" + multipartFile.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
} path +=multipartFile.getOriginalFilename();
}
AppiumConfig.setApkupload(path);
 

spring mvc框架+ ajax实现 文件上传的更多相关文章

  1. spring mvc 3.0 实现文件上传功能

    http://club.jledu.gov.cn/?uid-5282-action-viewspace-itemid-188672 —————————————————————————————————— ...

  2. Spring MVC—拦截器,文件上传,中文乱码处理,Rest风格,异常处理机制

    拦截器 文件上传 -中文乱码解决 rest风格 异常处理机制 拦截器 Spring MVC可以使用拦截器对请求进行拦截处理,用户可以自定义拦截器来实现特定的功能,自定义的拦截器必须实现HandlerI ...

  3. Spring MVC(四)文件上传

    文件上传步骤 1.写一个文件上传的页面 2.写一个文件上传的控制器 注意: 1.method="post" 2.enctype="multipart/form-data& ...

  4. 基于Spring Mvc实现的Excel文件上传下载

    最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring ...

  5. 6.MVC框架开发(文件上传)

    1.需要设置表单的enctype="multipart/form-data"属性 2.在控制器中获取表单文件中数据 [HttpPost] public ActionResult A ...

  6. ajax提交表单、ajax实现文件上传

    ajax提交表单.ajax实现文件上传,有需要的朋友可以参考下. 方式一:利用from表单的targer属性 + 隐藏的iframe 达到类似效果, 支持提交含有文件和普通数据的复杂表单 方式二:使用 ...

  7. Ajax 与文件上传

    一 Ajax篇 1 ajax简介(Asynchronous Javascript And XML) 异步,Js,XML,即使用Javascript语言与服务器进行异步交互,传输的数据为xml(可扩展标 ...

  8. 基于 Django的Ajax实现 文件上传

    ---------------------------------------------------------------遇到困难的时候,勇敢一点,找同学朋友帮忙,找导师求助. Ajax Ajax ...

  9. Struts2框架下的文件上传文件类型、名称约定

    Struts2框架下的文件上传机制:1.通过multipart/form-data form提交文件到服务器2.文件名是通过什么地方设置的?在strust2的FileUploadInterceptor ...

随机推荐

  1. HDU 2454 Degree Sequence of Graph G——可简单图化&&Heavel定理

    题意 给你一个度序列,问能否构成一个简单图. 分析 对于可图化,只要满足度数之和是偶数,即满足握手定理. 对于可简单图化,就是Heavel定理了. Heavel定理:把度序列排成不增序,即 $deg[ ...

  2. PHP 创建 MySQL 表

    CREATE TABLE 语句用于创建 MySQL 表. 创建表前,我们需要使用 use myDB 来选择要操作的数据库: use myDB; 我们将创建一个名为 "MyGuests&quo ...

  3. 遍历器Iterator--指针对象

    一. 什么是遍历器 1. 遍历器对象(Iterator) 遍历器对象本质上是一个指针对象,该对象有一个next方法,调用next方法返回一个 含有value和done属性的对象{value: val/ ...

  4. ElasticSearch 集群环境搭建,安装ElasticSearch-head插件,安装错误解决

    ElasticSearch-5.3.1集群环境搭建,安装ElasticSearch-head插件,安装错误解决 说起来甚是惭愧,博主在写这篇文章的时候,还没有系统性的学习一下ES,只知道可以拿来做全文 ...

  5. learning scala How To Create Variable Argument Function - varargs :_ *

    Scala collection such as List or Sequence or even an Array to variable argument function using the s ...

  6. About & Ideas & Queries

    About Blog主现高一,文化课和OI啥都不会 本Blog主太懒,所以很多内容都缩在一个文章里,如数学.图论大礼包 https://wenku.baidu.com/view/56d76029647 ...

  7. Python基础之可接受任意数量参数的函数

    1. 可接受任意数量位置参数的函数 为了能让一个函数接受任意数量的位置参数,可以在参数部分使用“*”. def avg(first, *rest): return (first + sum(rest) ...

  8. cas系列-cas登出(四)

    跟登陆一样,登出操作也很重要.由于是多应用间操作,状态保持也是一个要点,根据登出的影响范围,可以将登出操作分为两类: 单应用登出 单点登出(多应用登出) 顾名思义,单应用登出即登出只影响被操作的应用会 ...

  9. ansible 主机正则

    ansible <pattern> -m <module_name> -a <arguments> 该功能主要针对Inventory的主机列表,案例如下: 1.AL ...

  10. zabbix(9)iterms(监控项)

    一.iterms key 监控项按参数来分有两种:带参数和不带参 按定义来分:zabbix自带和用户自定义 1)Key可以带参数,该参数为一个数组列表,可以同时传递多个参数,Key的格式如下: 既Ke ...