Springmvc模式上传和下载与enctype对比

网友投稿 426 2023-03-03

Springmvc模式上传和-与enctype对比

Springmvc模式上传和-与enctype对比

一般表单数据分为两类

enctype带文件上传的表单和不带enctype的传统表单,这两种提交的数据有着不同的样式,并且上传文件只能使用enctype。

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("utf-8");

resp.setContentType("text/html;charset=utf-8");

//服务器存储文件的地址,需自己定义

String savepath = this.getServletContext().getRealPath("/upload");

System.out.println(savepath);

//如果文件不存在,需要先进行判断,并创建,否则会出现空文件报错

File file=new File(savepath);

if(!file.exists()){

file.mkdir();

}

//工具类commons-fileupload包创建工厂对象

DiskFileItemFactory itemFactory=new DiskFileItemFactory();

ServletFileUpload upload=new ServletFileUpload(itemFactory);

//判断是不是传统表单

if(!ServletFileUpload.isMultipartContent(req)){

System.out.println("是传统的表单 没有上传功能");

return;

}

try {

//表单的各项数据对象,封装成集合

List list = upload.parseRequest(req);

for(FileItem item:http://list){

//是普通的表单数据

if(item.isFormField()){

String fieldName = item.getFieldName();

String value = item.getString("utf-8");

System.out.println(fieldName+" "+value);

}else {

String filename = item.getName();//上传的文件名字

if(filename==null||filename.trim().equals("")){

// 当前上传的文件为空

continue;

}

System.out.println(filename);

//得到文件的名字

filename = filename.substring(filename.lastIndexOf("\\")+1);

InputStream in = item.getInputStream();

OutputStream out=new FileOutputStream(savepath+"\\"+filename);

byte[] buf=new byte[1024];

int len=0;

while((len=in.read(buf))>0){

out.write(buf,0,len);

}

in.close();

out.close();

}

}

} catch (FileUploadException e) {

e.printStackTrace();

}

req.getRequestDispatcher("/downloadlist").forward(req,resp);

}

上传文件的大致上,是将提交的文件转存到服务器端的一个文件目录下。然后转发到展示页面供选择。

-文件的一些设置

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("utf-8");

resp.setContentType("text/html;charset=utf-8");

//获取前台文件所展示的文件名称和存储目录下的名称要一致,方便写参数-。

String fileName= req.getParameter("file");

//先获取上传目录路径

String basePath = getServletContext().getRealPath("/upload");

//如果文件名是中文,需要进行url编码,此操作是为了避免不同浏览器的-页面下文件乱码的情况

String agent = req.getHeader("User-Agent");

String filenameEncoder = "";

if (agent.contains("MSIE")) {

// IE浏览器

filenameEncoder = URLEncoder.encode(fileName, "utf-8");

filenameEncoder = filenameEncoder.replace("+", " "http://);

} else if (agent.contains("Firefox")) {

// 火狐浏览器

BASE64Encoder base64Encoder = new BASE64Encoder();

filenameEncoder = "=?utf-8?B?"

+ base64Encoder.encode(fileName.getBytes("utpwqcdzFSPPf-8")) + "?=";

} else {

// 其它浏览器

filenameEncoder = URLEncoder.encode(fileName, "utf-8");

}

//设置-的响应头

resp.setHeader("content-disposition", "attachment;fileName="+filenameEncoder);//此filenameEncoder必须经过转码处理

//获取一个文件输入

InputStream is = new FileInputStream(new File(basePath,fileName));

//获取response字节

OutputStream out = resp.getOutputStream();

byte[] b= new byte[1024];

int len =-1;

while((len=is.read(b))!=-1){

out.write(b,0,len);

}

//关闭流

out.close();

is.close();

}

-的设置上需要注意文件名的一些乱码问题,最主要的是区别于不同浏览器下的一些差异。需要对文件名转码处理。

还需要提前设置对浏览器的响应头,告知浏览器是一个文件。

resp.setHeader("content-disposition", "attachment;fileName="+filenameEncoder);

接触了springmvc模式后,对上面的上传与-进行优化

此处上传的功能依旧是采用表格上传。文件格式依旧是

后台则是

@RequestMapping("/upload")

public String upload(MultipartFile file,String userName,HttpServletRequest request) throws IOException {

String filename = file.getOriginalFilename();

String suffix = filename.substring(filename.lastIndexOf("."));

if(suffix.equalsIgnoreCase(".jpg")){

String uuid = UUID.randomUUID().toString();

//FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E://"+uuid+suffix));

file.transferTo(new File("D://"+System.currentTimeMillis()+suffix));//位置存储在硬盘上

// file.transferTo(new File(request.getServletContext().getRealPath("/")+"static/userImages/"+file));

// 存储在项目里的目录下

request.setAttribute("result","上传成功");

return "/result.jsp";

}else{

request.setAttribute("result","上传失败");

return "/result.jsp";

}

}

相比之前的传统式上传,springmvc模式下封装了许多繁琐的过程,通过transferTo即可实现一些相应的操作

而-也是相应的简化了许多

@RequestMapping("/download")

public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {

response.setHeader("content-disposition","attachment;filename="+filename);

ServletOutputStream outputStream = response.getOutputStream();

String path = request.getServletContext().getRealPath("images");

File file = new File(path,filename);

byte[] bytes = FileUtils.readFileToByteArray(file);

outputStream.write(bytes);

outputStream.close();

}

一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:VUE开发企业微信小程序(可以用vue开发微信小程序)
下一篇:app系统架构(app模块架构)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~