基于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;
		}
}



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
基于SSM框架的书籍分功能代码可以按照以下步骤进行编写: 1. 创建数据库表:首先在数据库中创建书籍信息表和分表。 2. 配置数据库连接和MyBatis框架:在项目中配置数据库连接和MyBatis框架,以实现对数据库的访问。 3. 编写实体:根据数据库中的表结构,编写与之对应的Java实体。 4. 编写Mapper文件:在MyBatis框架中,编写Mapper文件,实现对数据库的增删改查操作。 5. 编写Service接口和实现:在Service层中,编写书籍分功能的接口和实现,实现书籍分相关的业务逻辑。 6. 编写Controller:在Controller层中,编写书籍分相关的请求处理方法,接收前端请求,调用Service层的方法,返回响应结果。 以下是一个简单的示例: 1. 数据库表结构: ``` CREATE TABLE book ( id INT(11) PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), author VARCHAR(50), publisher VARCHAR(50), publish_date DATE, isbn VARCHAR(20), category_id INT(11) ); CREATE TABLE category ( id INT(11) PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) ); ``` 2. 实体: Book.java ```java public class Book { private int id; private String name; private String author; private String publisher; private Date publishDate; private String isbn; private int categoryId; // getter and setter methods } ``` Category.java ```java public class Category { private int id; private String name; // getter and setter methods } ``` 3. Mapper文件: BookMapper.xml ```xml <mapper namespace="com.example.mapper.BookMapper"> <insert id="insert" parameterType="Book"> INSERT INTO book(name, author, publisher, publish_date, isbn, category_id) VALUES(#{name}, #{author}, #{publisher}, #{publishDate}, #{isbn}, #{categoryId}) </insert> <delete id="deleteById" parameterType="int"> DELETE FROM book WHERE id=#{id} </delete> <update id="update" parameterType="Book"> UPDATE book SET name=#{name}, author=#{author}, publisher=#{publisher}, publish_date=#{publishDate}, isbn=#{isbn}, category_id=#{categoryId} WHERE id=#{id} </update> <select id="findById" parameterType="int" resultType="Book"> SELECT * FROM book WHERE id=#{id} </select> <select id="findByCategoryId" parameterType="int" resultType="Book"> SELECT * FROM book WHERE category_id=#{categoryId} </select> </mapper> ``` CategoryMapper.xml ```xml <mapper namespace="com.example.mapper.CategoryMapper"> <insert id="insert" parameterType="Category"> INSERT INTO category(name) VALUES(#{name}) </insert> <delete id="deleteById" parameterType="int"> DELETE FROM category WHERE id=#{id} </delete> <update id="update" parameterType="Category"> UPDATE category SET name=#{name} WHERE id=#{id} </update> <select id="findById" parameterType="int" resultType="Category"> SELECT * FROM category WHERE id=#{id} </select> <select id="findByName" parameterType="String" resultType="Category"> SELECT * FROM category WHERE name=#{name} </select> </mapper> ``` 4. Service接口和实现: BookService.java ```java public interface BookService { void addBook(Book book); void deleteBook(int id); void updateBook(Book book); Book getBookById(int id); List<Book> getBooksByCategoryId(int categoryId); } ``` BookServiceImpl.java ```java @Service public class BookServiceImpl implements BookService { @Autowired private BookMapper bookMapper; @Override public void addBook(Book book) { bookMapper.insert(book); } @Override public void deleteBook(int id) { bookMapper.deleteById(id); } @Override public void updateBook(Book book) { bookMapper.update(book); } @Override public Book getBookById(int id) { return bookMapper.findById(id); } @Override public List<Book> getBooksByCategoryId(int categoryId) { return bookMapper.findByCategoryId(categoryId); } } ``` CategoryService.java ```java public interface CategoryService { void addCategory(Category category); void deleteCategory(int id); void updateCategory(Category category); Category getCategoryById(int id); Category getCategoryByName(String name); } ``` CategoryServiceImpl.java ```java @Service public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryMapper categoryMapper; @Override public void addCategory(Category category) { categoryMapper.insert(category); } @Override public void deleteCategory(int id) { categoryMapper.deleteById(id); } @Override public void updateCategory(Category category) { categoryMapper.update(category); } @Override public Category getCategoryById(int id) { return categoryMapper.findById(id); } @Override public Category getCategoryByName(String name) { return categoryMapper.findByName(name); } } ``` 5. Controller: BookController.java ```java @Controller @RequestMapping("/book") public class BookController { @Autowired private BookService bookService; @Autowired private CategoryService categoryService; @GetMapping("/list") public String list(Model model, int categoryId) { List<Book> books = bookService.getBooksByCategoryId(categoryId); Category category = categoryService.getCategoryById(categoryId); model.addAttribute("books", books); model.addAttribute("category", category); return "book/list"; } @GetMapping("/add") public String add(Model model) { List<Category> categories = categoryService.getAllCategories(); model.addAttribute("categories", categories); return "book/add"; } @PostMapping("/add") public String add(Book book) { bookService.addBook(book); return "redirect:/book/list?categoryId=" + book.getCategoryId(); } @GetMapping("/edit") public String edit(Model model, int id) { Book book = bookService.getBookById(id); List<Category> categories = categoryService.getAllCategories(); model.addAttribute("book", book); model.addAttribute("categories", categories); return "book/edit"; } @PostMapping("/edit") public String edit(Book book) { bookService.updateBook(book); return "redirect:/book/list?categoryId=" + book.getCategoryId(); } @GetMapping("/delete") public String delete(int id) { Book book = bookService.getBookById(id); bookService.deleteBook(id); return "redirect:/book/list?categoryId=" + book.getCategoryId(); } } ``` 以上是一个简单的基于SSM框架的书籍分功能代码示例,具体实现需要根据实际情况进行调整和优化。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NewTech精选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值