服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用Ajax进行文件与其他参数的上传功能(java开发)

使用Ajax进行文件与其他参数的上传功能(java开发)

2020-07-24 12:19難得丿糊塗灬 Java教程

这篇文章主要介绍了使用Ajax进行文件与其他参数的上传功能(java开发),非常不错,具有参考借鉴价值,需要的朋友参考下吧

文件上传:

记得前一段时间,为了研究Ajax文件上传,找了很多资料,在网上看到的大部分是form表单的方式提交文件,对于Ajax方式提交文件并且也要提交表单中其他数据,发现提及的并不是很多,后来在同事的帮助下,使用ajaxfileupload最终完成了文件上传与其他提交的操作,现在分享给大家,希望大家能有有所帮助。

操作步骤:

1 导入jar包:

我们在使用文件上传时,需要使用到两个jar包,分别是commons-io与commons-fileupload,在这里我使用的两个版本分别是2.4与1.3.1版本的,需要使用JS文件与jar包最后会发给大家一个连接(如何失效请直接我给留言,我会及时更改,谢谢)。

2 修改配置文件:

当我们导入的jar包是不够的,我们需要使用到这些jar包,由于我当时使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具体配置方法如下:

?
1
2
3
4
5
6
7
8
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize">
   <value>104857600</value>
  </property>
  <property name="maxInMemorySize">
   <value>4096</value>
  </property>
 </bean>

3 JSP文件:

大家对form表单提交问价的方式很熟悉,但是我们有很多情况下并不能直接使用form表单方式直接提交。这时候我们就需要使用Ajax方式提交,Ajax有很多的好处,比如当我们不需要刷新页面获希望进行局部刷新的时候,我们就可以使用Ajax。下面是我的表单提交的JSP页面,其中包含JS的详细步骤和HTML文件:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
<%@ page language="java" contentType="text/html; charset=GBK"
 pageEncoding="GBK"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="../commons/taglibs.jsp"%>
<!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=GBK">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>发布资讯</title>
 <script type="text/javascript" src="${ctx}/resources/new_js/jquery.js"></script>
 <script type="text/javascript" src="${ctx}/resources/js/ajaxfileupload.js"></script>
 <script type="text/javascript">
 function save(){
  var typeId = $("#type_span_info").attr("data-id");
   if (typeof (typeId) == "undefined") {
   $("#type_p_info").show();
   return;
  } else {
   $("#type_p_info").hide();
  }
  var id="codetool">

上面的代码是我在项目实际开发的过程中所用的代码,具体的CSS文件与JS文件我已经删掉了,但是不会影响具体的操作,大家使用的时候只需要把其中的class文件删掉了就可以了。好了,我们在说一说上面的代码。首先为大家解释一下ctx的作用,在我们项目开发的过程中,我们要求必须使用绝对路径,所有{ctx}是我们封装好的一个东西,就是我们的服务器地址+端口号+项目名称。当我们使用的时候,只需要引用一下文件,就是上面直接使用的<%@ include file=”../commons/taglibs.jsp”%>,当我们用的时候直接使用${ctx}就可以,大家在使用的时候就直接使用自己的本机地址端口号与项目名称就可以。后面的/resources/new_js/jquery.js就是我们要使用的jqery.js文件的存放地址。
其实在上面的Ajax的操作中,我相当于做了两次的Ajax的提价,但是在第一次提交的时候,后台给我们返回一个参数,就是我们的文件存放路径与文件名称,在第二次提交的时候,我们将这些参数与其他参数同时上传到后台,并将这些参数保存到数据库中,以便我们使用。

* 4 后台代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//文件上传
@RequestMapping(value = "/doUpload", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
@ResponseBody
 public String doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
  List<String> fileNames = null;
  if (request instanceof MultipartHttpServletRequest) {
   // process the uploaded file
   logger.info("=====进入文件类型选择=====");
   fileNames = uploadAttachment(request, "file");
  }
  String url = "";
  if (fileNames.size() > 0) {
   for (int i = 0; i < fileNames.size(); i++) {
    url = url + fileNames.get(i);
    if(i < fileNames.size() - 1){
     url = url + ",";
    }
   }
  }
  return url;
 }
//文件上传的工具类
public List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException {
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  List<MultipartFile> files = multipartRequest.getFiles(type);
  logger.info("数据长度========>>>>>>>>>>" + files.size());
  Calendar now = Calendar.getInstance();
  int year = now.get(Calendar.YEAR);
  int month = now.get(Calendar.MONTH) + 1;
  String realPath = PropertiesUtil.getProperty("realPath");
  System.err.println("realpath=====>>>>>" + realPath);
  //String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\" + type + "\" + year+ "\" + month + "\";
  String savePath = "government"+ File.separator + "image"+ File.separator + year+ File.separator + month + File.separator;
  logger.info("保存路径=====>" + savePath);
  List<String> fileNames = new ArrayList<String>();
  for (MultipartFile multipartFile : files) {
   logger.info("--" + multipartFile.getOriginalFilename());
   String fileName = multipartFile.getOriginalFilename();
   String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
   String custName = "" + System.currentTimeMillis() + "." + prefix;
   if (UsedUtil.isNotNull(fileName)) {
    File targetFile = new File(realPath+savePath, custName);
    // fileName = year+"-"+month+"-"+fileName;
    if (!targetFile.exists()) {
     targetFile.mkdirs();
     multipartFile.transferTo(targetFile);
    }
    try {
    } catch (Exception e) {
     e.printStackTrace();
    }
    fileNames.add(savePath + custName);
   }
  }
  return fileNames;
 }
//添加咨询
@RequestMapping(value = "/addInfo", method = RequestMethod.POST)
@ResponseBody
 public Integer addInfo(HttpServletRequest request, HttpServletResponse response,
   @RequestParam String fileUrl) {
  InfoBean bean = new InfoBean();
  if(UsedUtil.isNotNull(fileUrl)){
   bean.setImagePath(fileUrl);
  }
  Map<String, Object> paramMap = ControllerUtil.request2Map(request);
  bean.setTitle((String) paramMap.get("title"));
  bean.setSummary((String) paramMap.get("summary"));
  bean.setContent((String) paramMap.get("content"));
  bean.setTypeId((String)paramMap.get("typeId"));
  return infoService.insInfo(bean);
 }

在上面的代码中我们可以看到,在文件第一次上传的过程中,我们首先进入到doUpload中,然后使用uploadAttachment工具类,并将文件上传到服务器中,在上传的过程中,我首先做了一个文件唯一名称的操作,就是获取当前时间的毫秒数,虽然不能绝对保证,但是到并发量小的时候可以保证不会造成文件名称重复。然后,我将文件上传的路径的上传地址写到了.properties中,这样的好处是当我们想更换文件上传的路径时,我们就可以直接修改.properties文件,而读取.properties文件的具体方式在我的另一篇文章中讲到。最后,我们在开发的过程中,文件保存一般是保存到文件服务器中,而文件服务器一般是在Linux中,而在不同的服务器中,路径是使用斜杠还是反斜杠是不同的,所有我在这里面使用了File.separator来代替,File.separator在不同的系统中可以自动生成斜杠获反斜杠。

以上所述是小编给大家介绍的使用Ajax进行文件与其他参数的上传功能(java开发),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/hhb1san14/article/details/54192341

延伸 · 阅读

精彩推荐