今天的重点主要是文件上传
一个是form表单上传
package demo.web; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.List; import java.util.UUID; @WebServlet("/upload") public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建ServletFileUpload对象(核心对象) //创建一个FileIteFactory接口的实现类对象 DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload servletFileUpload=new ServletFileUpload(factory); try { ListfileItems = servletFileUpload.parseRequest(req); //对解析后的结果进行处理 for (FileItem fileItem:fileItems){ //判断当前项是否为一个普通的表单字段 if(fileItem.isFormField()){ String fileName=fileItem.getFieldName(); String value=fileItem.getString("utf-8"); }else { //是文件就创建上传目录 String dirPath=this.getServletContext().getRealPath("/headerimgs"); File directory = new File(dirPath); if(!directory.exists()){ directory.mkdir(); } //获取上传的文件名 String fileName=fileItem.getName(); //以文件的方式保存图片到服务器磁盘 String fname= UUID.randomUUID().toString()+ fileName.substring(fileName.indexOf(".")); String path=this.getServletContext().getRealPath("/headerimgs/"+fname); File file = new File(path); //保存文件 fileItem.write(file); } } } catch (Exception e) { e.printStackTrace(); } } }
上面要注意文件类型,如果报错可以先试试设置格式
还有一个是ajax上传
今天主要用的这个,出现了很多问题。因为我用的普通三层架构,没有用框架。所以在网上找了很久
function upload(obj){ //html代码就不发出来l,没什么特别,id是跟图片一起绑定的,到时候根据id显示图片 var url=window.location.search var id if(url.indexOf("?")!=-1){ id=url.substr(url.indexOf("=")+1) }else { id=0 } //用的formData对象 var formData = new FormData(); formData.append('images', $('#previewImg')[0].files[0]); formData.append('id',id); layer.msg('图片上传中', {icon: 16}); $.ajax({ type:"post", processdata: false, //类型选择false,到时候可根据类型自动变换 contentType: false, cache:false, url:"/wygl/upload", data:formData, success:function(data){ alert(data) if(data.code==1000){ console.log(data.image_name); layer.closeAll('loading'); layer.msg(data.info,{icon:1,time:1000}); $("#pimages").attr('src',data.image_name); $("#avatar").val(data.image_name); $(".imgs").show(); return false; }else{ alert(data.image_name) layer.msg(data.info,{icon:2,time:4000}); } } }); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); Part images = request.getPart("images"); //form-data; name="images"; filename="bi-ad.gif" String header = images.getHeader("Content-Disposition"); // 获取原文件名 int start = header.lastIndexOf("=")+1; String name = header.substring(start).replace(""", ""); System.out.println(name); //是文件就创建上传目录 String dirPath=this.getServletContext().getRealPath("/wy/img"); File directory = new File(dirPath); if(!directory.exists()) { directory.mkdir(); } //生成随机文件名 String filename = UUID.randomUUID().toString().substring(6) + name; String realPath = this.getServletContext().getRealPath("/wy/img/" + filename); //写入磁盘 images.write(realPath); int id = Integer.parseInt(request.getParameter("id")); System.out.println(id); //String path = "img/"+filename; String string="{"code":1000,"image_name":""+filename+""}"; System.out.println(string); if(id>0){ boolean b = service.updatepicture(id, filename); if(b){ response.getWriter().write(string); } } } }
我现在根据这个可以上传文件,也把文件名传到数据库中了,但是在读取文件时却发生了错误,系统提示找不到路径,那么就是路径信息不对,暂时还不知道应该怎么解决这个问题,今天居然写了7个小时代码,真的很强啊
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)