我如何上传和检索文件(图像,音频和视频)在Spring MVC



我在Spring MVC框架中设计一个小应用程序。我有一个HTML页面,用户可以上传多个文件。

这是我的HTML文件:

<div class="form-group">
<label class="control-label col-sm-4" for="option1">Option 1:</label>
<div class="col-sm-4">
<form:input type="text" path="option1" class="form-control"/>
</div>
<div class="col-sm-4">
	<form:input type="file" path="img1" class="form-control" name="img1"/>
</div>
</div>
							
<div class="form-group">
<label class="control-label col-sm-4" for="option2">Option 2:</label>
<div class="col-sm-4">
<form:input type="text" path="option2" class="form-control"/>
</div>
<div class="col-sm-4">
<form:input type="file" path="img2" class="form-control" name="img2"/>
</div>
</div>

基于此代码,我允许用户上传2个文件。

我也有一个bean叫做McqItem.java:

public class McqItem {
  
  	private String option1;
	private String option2;
    private byte[] img1;
	private byte[] img2;
//with their getter and setters
}

在我的控制器中,我设计了一个方法,我将所有数据(option1和option 2)传递给bean,并从那里到模型,并将它们保存在我的DB

BUT:我不知道怎么保存文件。最好将它们保存在文件中。

谁能告诉我如何保存上传的文件?

您可以使用多部分文件上传来上传和保存文件。

     byte[] bytes = file.getBytes();
            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();

这个spring boot的例子是一个很好的例子

https://spring.io/guides/gs/uploading-files/

这就是我在链接

之后所做的

控制器:

@RequestMapping(value="/questionType/MCQ.do",method = RequestMethod.POST)
	public ModelAndView saveMCQuestion(@RequestParam("option1") String option1,@RequestParam("option2") String option2 ,@RequestParam("img1") MultipartFile img1,@RequestParam("img2") MultipartFile img2,@ModelAttribute McqItem mcqItem, HttpServletRequest request)throws IOException{
		ModelAndView modelAndView = new ModelAndView();
		QuizItem quizitem=(QuizItem)request.getSession().getAttribute("quizItem");
		mcqItem.setQuiz_id(String.valueOf(quizitem.getId()));
		QuizItem qType=(QuizItem)request.getSession().getAttribute("qTypeItem");
		mcqItem.setQType(qType.getItemType());
		
//begin the uploading section
		byte[] img1File=null;
		byte[] img2File=null;
		if(!img1.isEmpty() && !img2.isEmpty()){
		try{
			img1File= img1.getBytes();
			img2File=img2.getBytes();
			
			BufferedOutputStream stream= 
					new BufferedOutputStream(new FileOutputStream(new File(option1)));
			stream.write(img1File);
			stream.write(img2File);
			stream.close();
			System.out.println("Successful Upload");
		}catch(Exception e){
			return null;
		}	}
		
		
//end Uploading section
	
		projectDAO.saveQuestion(mcqItem);
		modelAndView.addObject("qtypeitem", new QuizItem());
		modelAndView.setViewName("project/qType");
		
		return modelAndView;
		
	}
	
基本上我的问题是,沿着我的文件,我有一个表格保存在数据库以及。

但是它给我这个错误:"当前请求不是一个多部分请求"

最新更新