import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
/**
* 批量上傳圖片文件
* @author hxw
*
*/
@Controller
public class sctppl {
/**
* @Description: 批量上傳圖片文件
* @author: huxw
* @date: 2018年11月23日
* @return:String
*/
@ResponseBody
@RequestMapping("/uploadImgList.html")
public String uploadPictureList(@RequestParam(value = "file", required = false) MultipartFile[] file,
HttpServletRequest request) {
System.out.println("上傳");
File targetFile = null;
String msg = "";// 返回存儲路徑
int code = 1;
List imgList = new ArrayList();
if (file != null && file.length > 0) {
for (int i = 0; i < file.length; i++) {
String fileName = file[i].getOriginalFilename();// 獲取文件名加後綴
if (fileName != null && fileName != "") {
/*
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath() + "/static/";// 存儲路徑
// String
String path = request.getSession().getServletContext().getRealPath("static"); // 文件存儲位置
*/
String returnUrl = "E:/files/";
String path ="E:/files/";
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());// 文件後綴
fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileF;// 新的文件名
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
// 先判斷文件是否存在
String fileAdd = formatter.format(currentTime);
//File file1 = new File(path + "/" + fileAdd);
File file1 = new File(path);
// 如果文件夾不存在則創建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdir();
}
targetFile = new File(file1, fileName);
try {
file[i].transferTo(targetFile);
msg = returnUrl + fileAdd + "/" + fileName;
imgList.add(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// return JSON.toJSONString(imgList);
return imgList.toString();
}
}