jQuery+Ajax+form表单上传文件简单demo,附前后端代码

jQuery+Ajax+form表单上传文件简单demo,附前后端代码

一,书写目的:
记录踩坑,,
二,代码的功能
使用ajax,和springBoot项目,从前端往后端传输文件
三,代码详情
前端代码:
html:

<form id="tf">
    <input type="file" name="uploadFile" id="photo">
    <input type="text" name="inputInfoName" id="inputInfo" placeholder ="请填写上传文件的备注信息">
    <input type="button" onclick="postData()" value="下一步">
</form>

ajax写法:

function postData() {
        var form = new FormData(document.getElementById("tf"));
        alert(form);
        $.ajax({
            url: "http://localhost:8080/input/file",
            type: "post",
            data: form,
            processData: false,
            contentType: false,
            success: function (data) {
                alert(JSON.stringify(data))
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

后端代码:
entity:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GrayFileQo {

    private String marks;//备注

    private MultipartFile multipartFile;

}
 /**
     * jQuery+Ajax+form表单上传文件,其余信息,从form表单里面放值
     * 在HttpServletRequest的.getParameter()方法中获取
     *
     * @param request
     * @return
     */
    @PostMapping("/input/file")
    @ApiOperation("上传文件")
    public Result inputFile(HttpServletRequest request) {

        MultipartHttpServletRequest multReq = (MultipartHttpServletRequest) request;
        MultipartFile file = multReq.getFile("uploadFile");
        GrayFileQo inputQo = new GrayFileQo();
        inputQo.setMultipartFile(file);
        inputQo.setMarks(multReq.getParameter("inputInfoName"));
        ServiceResult result = fileInputService.inputFileService(inputQo);
        return new Result(result);
    }

后端转储入参文件:

@Slf4j
@Service
public class FileInputServiceImpl implements FileInputService {


    @Override
    public ServiceResult inputFileService(GrayFileQo inputQo) {
        MultipartFile file = inputQo.getMultipartFile();
        File outFile = new File(GrayFileConstant.FILE_PATH + file.getOriginalFilename());
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        try {
            file.transferTo(outFile);
        } catch (IOException e) {
            log.error("===== 文件存盘异常 :", e);
        }
        return ServiceResult.success();
    }
}

前端通过form表单提交相关到后端,后端可以获取文件,和前端form表单内的信息,对应关系为:
在这里插入图片描述
ps:
下面写的代码仅供参考,如果遇到相同问题可以试试。
我自己搭建了一个springBootWeb项目,但是在前后端交互的时候,后端会提示xxhttpMessageConvert不能转换,(英文太长,记不住)。
处理方式:配置了HttpMessageConverter(大神勿喷,哈哈哈)

@Slf4j
@Component//@RestController这个注解返回json,但是新建项目的时候,直接用ajax请求,返回的不是json格式,
//ajax从返回的data去不了值,然后配置了这个GrayHttpMessageConverter,过后可以使用,然后不使用这个类,也一样可以了
//不同浏览器也能使用,排除缓存问题
public class GrayHttpMessageConverter implements HttpMessageConverter {


    @Override
    public boolean canRead(Class clazz, MediaType mediaType) {
        boolean assignableFrom = clazz.isAssignableFrom(Result.class);
//        System.out.println("canRead" + assignableFrom);
//        if (mediaType != null) {
//            System.out.println("canWrite" + mediaType.hashCode());
//        }
//        System.out.println("canWrite" + mediaType);
        return true;
    }

    @Override
    public boolean canWrite(Class clazz, MediaType mediaType) {
        boolean assignableFrom = clazz.isAssignableFrom(Result.class);
//        System.out.println("canWrite" + assignableFrom);
//        if (mediaType != null) {
//            System.out.println("canWrite" + mediaType.hashCode());
//        }
//        System.out.println("canWrite" + mediaType);
        return assignableFrom;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        //暂时不知道怎么用 2021/3/11
        List<MediaType> types = new ArrayList<>();
        MediaType json = new MediaType("application", "*+json");
        MediaType urlencoded = new MediaType("application", "*+x-www-form-urlencoded");
        MediaType multipart = new MediaType("application", "*+form-data");
        types.add(json);
        types.add(urlencoded);
        types.add(multipart);
        return types;
    }

    @Override
    public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

//        if (contentType != null) {
//            System.out.println("write" + contentType.hashCode());
//        }
        System.out.println("write" + contentType);
        if (o instanceof Result) {
            System.out.println("难道是这样???");//就是这样
            OutputStream outputStream = outputMessage.getBody();
            String backStr = JSON.toJSONString(o);
            outputStream.write(backStr.getBytes());
        }

    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值