栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

利用SpringMVC和Ajax实现文件上传功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用SpringMVC和Ajax实现文件上传功能

个人根据相关资料实现利用SpringMVC和Ajax实现文件上传功能:

环境:

1.JDK1.7

2.maven3.3.9

3.Tomcat7

第一步:

导入相关jar包:

第二步:

配置springmvc-config.xml



 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

第三步:

配置web.xml



 fileupload
 
 index.html
 index.htm
 index.jsp
 default.html
 default.htm
 default.jsp
 
 
 
 springDispatcherServlet
 org.springframework.web.servlet.DispatcherServlet
 
  contextConfigLocation
  classpath:springmvc-config.xml
 
 1
 
 
 springDispatcherServlet
 /
 
 
 

第四步:

新建一个Controller类,并实现文件上传的功能

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
 
import javax.json.Json;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
 
@Controller
public class FileUploadController {
 
 @RequestMapping(value = "index", method = RequestMethod.GET)
 public String index() {
 return "index";
 }
 
 @RequestMapping(value = "/upload", method = RequestMethod.POST)
 @ResponseBody
 public String upload(@RequestParam("file") MultipartFile file,
  HttpServletRequest request) {
 Map modelMap = new HashMap<>();
 if (!file.isEmpty()) {
  String storePath = "E://images";
  Random r = new Random();
  String fileName = file.getOriginalFilename();
  String[] split = fileName.split(".jpg");
  fileName = split[0] + r.nextInt(1000);
  fileName = fileName + ".jpg";
  File filePath = new File(storePath, fileName);
  if (!filePath.getParentFile().exists()) {
  filePath.getParentFile().mkdirs();// 如果目录不存在,则创建目录
  }
  try {
  file.transferTo(new File(storePath + File.separator + fileName));// 把文件写入目标文件地址
  } catch (Exception e) {
  e.printStackTrace();
  modelMap.put("back", "error");
  String json = JSON.toJSonString(modelMap);
  return json;
  }
  modelMap.put("back", "success");
 
 } else {
  modelMap.put("back", "error");
 }
 String json = JSON.toJSonString(modelMap);
 return json;
 
 }
 
}

第五步: 

在WEB-INF下,新建一个pages文件夹,并创建实现文件上传的jsp或者HTML文件(我使用的是jsp):

在index.jsp下写入相关的ajax的方法,在使用ajax之前必须先导入js库。


 
 

第六步:

进行测试

上传文件

上传成功

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137218.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号