springmvc文件上传,json数据交互

一 Springmvc文件上传

    在学习servlet的时候,文件上传依赖fileupload和io的jar包。这里回忆一下之前学习的知识点:

                //创建工厂对象

                DiskFileItemFactory factory = new DiskFileItemFactory();

                // 用于操作上传的流

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024*60);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
// 判断表单项的类型
if (item.isFormField()) {
                                        //表单类型数据处理代码块
} else {
// 保存到服务器
InputStream is = item.getInputStream();
//使用UUID
String fileName = UUID.randomUUID().toString();
//截取上传文件的格式
String upFileName = item.getName();
String[] split = upFileName.split("\\.");
String lastName=split[split.length-1];
//保存到数据库
String realPath = "d:/head/"+fileName+"."+lastName;
//保存到seesion的路径
String savepath="http://192.168.2.87:8080/"+fileName+"."+lastName;
request.getSession().setAttribute("imgPath", savepath);
System.out.println(savepath);
OutputStream os = new FileOutputStream(realPath);
/* byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.close();*/
IOUtils.copy(is, os);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
        springmvc提供了内置的文件上传解析器。首先jsp代码就不贴上了,几个注意点:文件上传提交方式要改成POST,而且表单中要加入enctype="mutipart/form-data"属性。
        servlet3.0之后,官方提示可以不再依赖第三方组件,直接使用Servlet3.0提供的API实现文件上传功能。结合springmvc框架,进行测试。代码如下:
        web.xml中新增配置如下:
         
multipart-config的其他属性没配,例如:fileSizeThershold:当前数据量大于该值时,内容将被写入文件。
                                                                         maxRequestSize:针对 multipart/form-data 请求的最大数量,默认为-1,表示没有限制

配置MultipartResolver解析器:

FileUploadController类:

@Controller
public class FileUploadController {
@RequestMapping("/form")
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
throws IOException {
File f = new File("D:\\img\\"+file.getOriginalFilename());
file.transferTo(f);
return "upload";
}
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String index() {
return "upload";
}
}

jsp页面写一下,测试 D盘文件上传成功!!!

扫描二维码关注公众号,回复: 1726141 查看本文章


二 json数据交互

    首先找到依赖jar包

    

    

还需要在任何一个处理器适配器里配置:


<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.mvc.controller.DateBinder" />
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>


@Controller
public class JsonController {
@RequestMapping("/json")
public void request(@RequestBody Pet json, HttpServletResponse response) throws IOException {
//response.getWriter().write(json);
System.out.println(json);
response.getWriter().write("ok");
}
}

我是通过Postman这款软件来测试请求体,你们可自行下载。

猜你喜欢

转载自blog.csdn.net/weixin_42010394/article/details/80776284