servlet+springmvc文件上传

前端

为了好观看,格式加了回车

      <form action="#" id="form1" onsubmit="false" 
      enctype="multipart/form-data" method="post">
        <div class="add">
          <span class="add_tit">再次确认水果编号并绑定图片 
          :</span>
          <span class="add_text"><input type="text"
           name="fid"  value="" /></span>
        </div>
        <div class="add">
          <span class="add_tit">图片:</span>
          <input id="file3" type="file" class="form-control" 
          name="file" multiple="multiple" accept=".pdf,.zip,.xls,
          .doc,.txt,.png,.jpg "/>
        </div>
      </form>
$("#file3").change(function() {
            var formdata = new 
            FormData(document.getElementById("form1"));
            $.ajax({
              type: 'post',
              url: '/x-test/BSServlet?key=addimg',
              data:formdata,
              processData: false,
              contentType: false,
              success: function (result) {
                if (result && result.success) {
                  window.alert("分类删除成功");
                  window.location.reload();
                } else {
                  window.alert(result.msg || '分类删除失败')
                }
              }
            });
          })

需要设置
1.enctype=“multipart/form-data”

form表单中enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
enctype有三个属性application/x-www-form-urlencoded,multipart/form-data,text/plain
这里设置了就相当于下面设置了contentType

这里使用change函数是为了当点击
在这里插入图片描述
选择文件时,选好了文件就发请求。
这里我们是将请求转化成了FormData
这里既可以传键值对形式的数据,又可以包含二进制数据

ajax各字段的意思

contentType: 告诉服务器,我要发什么类型的数据
contentType 常见的格式

text/plain :纯文本格式
application/json: JSON数据格式
application/x-www-form-urlencoded
中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
multipart/form-data : 需要在表单中进行文件上传时,就需要使用

json------
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json' // 需要主动设置
,并且将object 用JSON.stringify(data)进行转化
})

dataType:告诉服务器,我要想什么类型的数据,如果没有指定,那么会自动推断是返回 XML,还是JSON,还是script,还是String。
processData:

在使用jQuery的$.ajax()方法的时候参数processData默认为true(该方法为jQuery独有的)
默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded
如果想发送不想转换的的信息的时候需要手动将其设置为false

一些提交表单常用的Api包装数据

1.JQuery的方法serialize()
序列化一个表单,序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中,这样在ajax提交表单数据时,就不用一一列举每一个参数,只需将data参数设置为:$(“form”).serialize()即可。

2.FormData
这个方法可以上传文件
FormData 对象,不能使用 GET 方式

 var formdata = new FormData(document
 .getElementById("form1"));
            $.ajax({
              type: 'post',
              url: '/x-test/BSServlet?key=addimg',
              data:formdata,
              processData: false,
              contentType: false,
              success: function (result) {
                if (result && result.success) {
                  window.alert("分类删除成功");
                  window.location.reload();
                } else {
                  window.alert(result.msg || '分类删除失败')
                }

后台

servlet

Collection<Part> parts = req.getParts(); 
part.getContentType() 若是文件则获取文件类型
part.getInputStream() 得到的结果是流
@MultipartConfig //不加getpart获取不到数据
public class BSServlet extends HttpServlet {
Collection<Part> parts = req.getParts(); 
        if (parts != null) {
            for (Part part : parts) {
                //判断是文件还是字段
                if (part.getContentType() == null) {
                    //字符
                    InputStreamReader c = new InputStreamReader(part.getInputStream(), "utf-8");
                    BufferedReader b = new BufferedReader(c);
                    index = b.readLine();
                    System.out.println(index);
                    File dir = new File(req.getServletContext().getRealPath("img\\fruits\\"+index));
                    //判断当前目录是否存在
                    if (!dir.exists()) {
                        //目录不存在,需要创建
                        dir.mkdirs();
                        System.out.println("创建文件成功");
                    }
                } else {
                    File dirimg = new File(req.getServletContext().getRealPath("img\\fruits\\"+index+"\\" + "(" + i + ")" + ".jpg"));
                   in = new BufferedInputStream(part.getInputStream());
                     out = new BufferedOutputStream(new FileOutputStream(dirimg));
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = in.read(b)) != -1) {
                        out.write(b, 0, len);
                    }
                    System.out.println("写入图片成功");
                    i++;

                }
            }
                out.close();
                in.close();


            }

@MultipartConfig //不加getpart获取不到数据

注意:
在拿到前端文件并在后台设置文件路径时要设置到对应的out或者target目录中
req.getServletContext().getRealPath(“img\fruits\”+index)

SpringMvc

MultipartFile为org.springframework.web.mutipart包下的一个类,也就是说如果想使用MultipartFile这个类就必须引入spring框架,换句话说,如果想在项目中使用MultipartFile这个类,那么项目必须要使用spring框架才可以,否则无法引入这个类。MultipartFile翻译成中文来讲就是“多组件的文档”,不用太在乎他的中文含义,一般来讲使用MultipartFile这个类主要是来实现以表单的形式进行文件上传功能。

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在,需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值