package com.itheima.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.Resource;
import com.itheima.utils.JSONFileUtils;
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;import java.io.File;import java.util.ArrayList;
import java.util.List;
@Controllerpublic class FileController { //上传文件 @RequestMapping("/fileUpLoad")
public String fileUpLoad(MultipartFile[] files, HttpServletRequest request) throws Exception{
String path="D:\\idea项目保存位置\\MVC\\src\\main\\webapp\\files\\";
ObjectMapper mapper = new ObjectMapper();
//判断files为空,如果为空,上传失败;否则才开始进行上传操作
if (files!=null && files.length>0){
//开始文件上传操作
//遍历每个文件
for (MultipartFile file:files){
String filename=file.getOriginalFilename();
ArrayList<Resource> list = new ArrayList<>(); String json= JSONFileUtils.readFile(path+"/files.json"); if (json.length()!=0){
list=mapper.readValue(json,
new TypeReference<List< Resource >>() { });
for (Resource resource:list){
if (filename.equals(resource.getName())){ String[] split=filename.split("\\."); filename=split[0]+"(1)."+split[1];
}
}
}
String filepath=path+filename;
file.transferTo(new File(filepath));
list.add(new Resource(filename));
json=mapper.writeValueAsString(list);
JSONFileUtils.writeFile(json,path+"/files.json"); }
request.setAttribute("msg","(上传成功)");
return "forward:fileload.jsp"; }
request.setAttribute("msg","(上传失败)");
return "forward:fileload.jsp"; }
@ResponseBody
@RequestMapping(value = "/getFilesName",
produces = "text/html;charset=utf-8")
public String getFilesName(HttpServletRequest request, HttpServletResponse response) throws Exception{
String path="D:\\idea项目保存位置\\MVC\\src\\main\\webapp\\";
String json=JSONFileUtils.readFile(path);
return json; }
`
运行结果是这样的,就是下载那里显示不出来
然后在我的项目那里可以看到上传的图片
我的jsp是这样的