前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >文件上传

文件上传

作者头像
微醺
发布2019-01-17 13:12:23
3.6K0
发布2019-01-17 13:12:23
举报

文件(图片)的上传方法

首先创建一个servlet用来获取从前端(form表单或者其它方法)传过来的数据,我这里用到人员信息的提交,使用的是form表单。 前端代码form

代码语言:javascript
复制
  <form method="post" class="form-x"  encType="multipart/form-data" action="people.do">    
      <div class="form-group">
        <div class="label">
          <label>姓名:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50" name="name"  data-validate="required:请输入姓名" />
          <div class="tips"></div>
        </div>
      </div>
       <div class="form-group">
        <div class="label">
          <label>性别:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50"  name="sex" data-validate="required:请输入性别" />
          <div class="tips"></div>
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label>年龄:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50" name="age" data-validate="required:请输入年龄" />
          <div class="tips"></div>
        </div>
      </div>
        <div class="form-group">
        <div class="label">
          <label>部门:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50"  name="depart" data-validate="required:请输入部门" />
          <div class="tips"></div>
        </div>
      </div>
         <div class="form-group">
        <div class="label">
          <label>手机号码:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50"  name="phone" data-validate="required:请输入手机号码" />
          <div class="tips"></div>
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label>email:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50"  name="email" data-validate="required:请输入email" />
          <div class="tips"></div>
        </div>
      </div>      
      <div class="form-group">
        <div class="label">
          <label>图片:</label>
        </div>
        <div class="field">
          <input type="file" id="url1" name="img" class="input tips button bg-blue margin-left" style="width:25%; float:left;" data-toggle="hover" data-place="right" data-image="" />
          <div class="tipss">图片尺寸:1920*500</div>
        </div>
      </div>
      
      <div class="form-group">
        <div class="label">
          <label></label>
        </div>
        <div class="field">
          <button class="button bg-main icon-check-square-o" type="submit"> 提交</button>
        </div>
      </div>
    </form>

servlet代码

代码语言:javascript
复制
  import java.io.IOException;   
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    import com.tf.management.dao.PeopleImp;
    import com.tf.management.entity.Person;
    import com.tf.management.util.UploadImg;
 
    @WebServlet("/people.do")
    @MultipartConfig//注解,这里必须用到多部分上传,因为文件太大,一次传递不完
    public class PeopleServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;        
    	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		//从前端获取数据
    		String name = req.getParameter("name");
    		String age = req.getParameter("age");
    		String sex = req.getParameter("sex");
    		String depart = req.getParameter("depart");
    		String phone = req.getParameter("phone");
    		String email = req.getParameter("email");
    		//获取图片
    		Part part = req.getPart("img");
    		String path = req.getServletContext().getRealPath("img");//获取图片的路径
    		String icon = new UploadImg().uploadImg(part, path);//调用上传图片的方法,返回一个相对路径
    		//处理数据 把数据封装成people对象
           Person person = new Person();
       	   person.setName(name);
	       person.setAge(Integer.valueOf(age));
	       person.setSex(sex);
	       person.setDepart(depart);
	       person.setEmail(email);
	       person.setPhone(phone);
	       person.setIcon(icon);
	      //插入到数据库中
	      new PeopleImp().update(person);
	     //跳转到adv.html页面
	     req.getRequestDispatcher("adv1.html").forward(req, resp);
    	}
 }

上传图片方法

代码语言:javascript
复制
import java.io.File;
import java.io.IOException;
import javax.servlet.http.Part;

public class UploadImg {
	//上传文件
	public String uploadImg(Part part,String path) {
	//2.3通过文件的content-type,判断文件的类型,不是图片类型不让上传
	String type=part.getContentType();
	if (!(type.contains("png")||type.contains("jpeg")||type.contains("gif"))) {
	//返回前端文件必须是指定格式	
	return null;
	}
	//2.4判断文件大小,可以限制图片的大小
	if (part.getSize()>256*768) {
	return null;//如果太小,上传不上去
	}
	//2.5将文件进行拼接写入到指定文件
	//处理字符串,获取上传的文件名
	String content=part.getHeader("content-disposition");//获取文件绝对路径
	String filename=content.substring(content.lastIndexOf("=\"")+2,content.lastIndexOf("\""));//截取文件名称	
	String newFile="img/"+filename;	
	File file=new File(path);
	if (!file.exists()) {//不存在当前文件,新建一个
	file.mkdir();
	}
	filename=path+File.separatorChar+filename;//File.separetorChar是反斜杠,这里在windows和苹果系统都适用
	//2.6将文件写到指定位置
	try {
	part.write(filename);
	} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}
	return newFile;//返回文件路径
	}
}

总结

文件上传的时候一定要记住使用注解,@MultipartConfig多部分上传一定不能少。文件存取到数据库中是相对路径,数据库会根据相对路径在把图片显示在前端。主要注意的是相对路径的拼接。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文件(图片)的上传方法
  • 上传图片方法
  • 总结
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档