把文件上传到网页(把文件上传到网页上)

把文件上传到网页(把文件上传到网页上)DOCTYPE html html head meta charset UTF 8 title 上传文件 title head body form action uploadServle method post enctype multipart form data nbsp 文件 input type file name myfile nbsp input



<!DOCTYPE html>
html
head
meta charset="UTF-8"
title上传文件title
head
body
form action="uploadServlet" method="post" enctype="multipart/form-data"
 文件:input type="file" name="myfile"
 input type="submit" value="上传"
form
body
html

public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // 设定编码,可以获取中文文件名
 request.setCharacterEncoding("UTF-8");
 // 获取tomcat下的upload目录的路径
 String path = getServletContext().getRealPath("/upload");
 // 临时文件目录
 String tempPath = getServletContext().getRealPath("/temp");
 // 检查我们是否有文件上传请求
 // boolean isMultipart = ServletFileUpload.isMultipartContent(req);
 // 1、声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录
 DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
 // 2、声明ServletFileUpload,接收上面的临时文件。也可以默认值
 ServletFileUpload up = new ServletFileUpload(disk);
 // 3、解析request
 try {
  List<FileItem> list = up.parseRequest(request);
  if (list.size() > 0) {
   for (FileItem file : list) {
    // 判断是否是普通的表单项
    if (file.isFormField()) {
     String fieldName = file.getFieldName();
     // 中文乱码,此时还需要指定获取数据的编码方式
     // String value = file.getString();
     String value = file.getString("UTF-8");
     System.out.println(fieldName + "=" + value);
    } else { // 说明是一个文件
     // 获取文件本身的名称
     String fileName = file.getName();
     System.out.println(file.getFieldName());
     // 处理文件名称
     fileName = fileName.substring(fileName.lastIndexOf("\") + 1);
     System.out.println("old Name : " + fileName);
     // 修改名称
     String extName = fileName.substring(fileName.lastIndexOf("."));
     String newName = UUID.randomUUID().toString().replace("-", "") + extName;
     // 保存新的名称,并写出到新文件中
     file.write(new File(path + "/" + newName));
     System.out.println("文件名是:" + fileName);
     System.out.println("文件大小是:" + file.getSize());
     file.delete();
    }
   }
  }
 } catch (FileUploadException e) {
  e.printStackTrace();
 } catch (Exception e) {
  e.printStackTrace();
 }
}

}

<!DOCTYPE html>
html
head
meta charset="UTF-8"
title上传文件title
head
body
form action="upload" method="post" enctype="multipart/form-data"
 姓名:input type="text" name="uname"
 文件:input type="file" name="myfile"
 input type="submit" value="上传"
form
body
html

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 System.out.println("上传文件...");
 // 设置编码
 request.setCharacterEncoding("UTF-8");
 // 获取普通表单项参数
 String uname = request.getParameter("uname");
 System.out.println(uname);
 // 上传文件
 // 得到part对象 request.getpart(name):name代表的是表单中file元素的name属性值
 Part part = request.getPart("myfile");
 // 得到文件存放的路径
 String path = request.getServletContext().getRealPath("/");
 // 得到文件名
 String fileName = part.getSubmittedFileName();
 // 上传
 part.write(path + fileName);
}

}

dependency

   groupIdcommons-fileuploadgroupId

   artifactIdcommons-fileuploadartifactId

   version1.3.2version

dependency

bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"

   property name="maxUploadSize"

   value104857600value

   property

   property name="maxInMemorySize"

   value4096value

   property

bean

import java.io.File;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;

import org.springframework.web.servlet.ModelAndView;

@Controller

public class FileController {

   @RequestMapping("/uploadFile")

   public ModelAndView uploadFile(HttpServletRequest request){

       ModelAndView mv=new ModelAndView();

       mv.setViewName("result");

       MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request;

       MultipartFile multipartFile= mr.getFile("file");

       String path=request.getSession().getServletContext().getRealPath("upload");

       System.out.println(path);

       if(null!=multipartFile&&!multipartFile.isEmpty()){

        String fileName=multipartFile.getOriginalFilename();

       try {

        multipartFile.transferTo(new File(path,fileName));

        mv.addObject("msg", "文件上传成功!");

       } catch (Exception e) {

        mv.addObject("msg", "上传失败!");

        e.printStackTrace();

       }

       }

       return mv;

}

}

form action="uploadFile" method="post" enctype="multipart/form-data"

input type="file" name="file"

button type="submit" 提交button

form


编程小号
上一篇 2025-04-11 13:33
下一篇 2025-02-08 19:11

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/50689.html