基於SSM框架的多文件上傳Controller類編寫

前端代碼
<form id="fileupload" action="/rest/pic/upload" method="POST" enctype="multipart/form-data">
        <!-- Redirect browsers with JavaScript disabled to the origin page -->
        <noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript>
        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
                <!-- The fileinput-button span is used to style the file input field as button -->
                <span class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <span>選擇文件(多選)</span>
                    <input type="file" name="uploadFile" multiple="multiple">
                </span>
                <button type="submit" class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>開始上傳</span>
                </button>
                <button type="reset" class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>取消上傳</span>
                </button>
                <button type="button" class="btn btn-danger delete">
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>刪除</span>
                </button> 
                <input type="checkbox" class="toggle" title="全選">
                <!-- The global file processing state -->
                <span class="fileupload-process"></span>
            </div>
            <!-- The global progress state -->
            <div class="col-lg-5 fileupload-progress fade">
                <!-- The global progress bar -->
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <!-- The extended global progress state -->
                <div class="progress-extended"> </div>
            </div>
        </div>
        <!-- The table listing the files available for upload/download -->
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>

Controller類

@Controller
@RequestMapping("pic")
public class FileUploadUtil{
	
	private static final Logger LOGGER = Logger.getLogger(FileUploadUtil.class);
	   @Value(value = "${IMAGE_BASE_URL}")
		private String IMAGE_BASE_URL;
		private String REPOSITORY_PATH;
		private static final ObjectMapper mapper = new ObjectMapper();

		@Autowired
		private ExportService exportService;
		// 允許上傳的格式
		private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" };

		@RequestMapping(value = "/upload", method = RequestMethod.POST)
		@ResponseBody
		public String upload(@RequestParam("uploadFile") MultipartFile[] uploadFile , HttpServletRequest request,HttpServletResponse response) throws Exception {
			REPOSITORY_PATH = request.getSession().getServletContext().getRealPath("upload");
			MultipartFile multipartFile = null;
			boolean isLegal = false;
			List<PicUploadResult> fileUploadResult = new ArrayList<>();
			PicUploadResult pic = null;
			ExportExcelConfig eec = new ExportExcelConfig();
			String urls = "";
			for (int i = 0; i < uploadFile.length; i++) {
				multipartFile = uploadFile[i];
				// 校驗圖片格式
				for (String type : IMAGE_TYPE) {
					if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
						isLegal = true;
						break;
					}
				}

				// 封裝Result對象,並且將文件的byte數組放置到result對象中
				pic = new PicUploadResult();

				// 狀態
				pic.setError(isLegal ? 0 : 1);

				// 文件新路徑
				String filePath = getFilePath(multipartFile.getOriginalFilename());

				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Pic file upload .[{}] to [{}] ."+multipartFile.getOriginalFilename());
				}

				// 生成圖片的絕對引用地址
				String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath,REPOSITORY_PATH), "\\", "/");
				pic.setUrl(IMAGE_BASE_URL + picUrl);

				File newFile = new File(filePath);

				// 寫文件到磁盤
				multipartFile.transferTo(newFile);

				// 校驗圖片是否合法
				isLegal = false;
				try {
					BufferedImage image = ImageIO.read(newFile);
					if (image != null) {
						pic.setWidth(image.getWidth() + "");
						pic.setHeight(image.getHeight() + "");
						isLegal = true;
					}
				} catch (IOException e) {
				}

				// 狀態
				pic.setError(isLegal ? 0 : 1);
				if(pic.getError()==0){
					urls+=pic.getUrl();
					if(i<2)
					urls+=",";
				}
				if (!isLegal) {
					// 不合法,將磁盤上的文件刪除
					newFile.delete();
				}
				fileUploadResult.add(pic);
			} 
			eec.setUrl(urls);
			eec.setCreateTime(new Date());
			exportService.addConfigInfo(eec);
			response.setContentType(MediaType.TEXT_HTML_VALUE);
			return mapper.writeValueAsString(fileUploadResult);
		}

		private String getFilePath(String sourceFileName) {
			String baseFolder = REPOSITORY_PATH;
			Date nowDate = new Date();
			// yyyy/MM/dd
			String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy") + File.separator + new DateTime(nowDate).toString("MM") + File.separator
					+ new DateTime(nowDate).toString("dd");
			File file = new File(fileFolder);
			if (!file.isDirectory()) {
				// 如果目錄不存在,則創建目錄
				file.mkdirs();
			}
			// 生成新的文件名
			String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
			return fileFolder + File.separator + fileName;
		}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章