2019-07-13-关于form-data的上传中文文件乱码的解决办法?


layout: post
title: 关于form-data的上传中文文件乱码的解决办法?
date: 2019-07-13 14:02:44 +0800
categories: 前端
tags: [“HTML”, “springboot”]
notebook: 前端
comments: false
description: 对内容的描述

问题汇总?

  • 关于form-data的上传中文文件乱码的解决办法?
  • 使用Jersey上传文件到tomcat的中文乱码问题?
  • Content-Disposition 文件上传、下载 中文乱码 HTTP头 解决办法?
  • 关于乱码的解决办法?
  • 文件上传小结?

使用表单测试,如果没有enctype=“multipart/form-data"会出现提交类型不符合。

<form action="http://127.0.0.1:8081/resource/file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="submit">
</form>

返回

{"code":0,"msg":"程序执行成功","data":null}

查看文件名,乱码

解决办法,找到文件名的编码,关于ASCII,所以解码就可以了。

new String(disposition.getFileName().getBytes("iso-8859-1"),"UTF-8");

输出正确了

答:解码就好了

文件上传所有后台代码(不需要看)

package me.xiongxiao.life.plan.resource;

//import org.apache.tomcat.util.http.fileupload.FileUtils;
import me.xiongxiao.life.plan.entity.Result.Code;
import me.xiongxiao.life.plan.entity.Result.Msg;
import me.xiongxiao.life.plan.entity.Result.RCM;
import me.xiongxiao.life.plan.entity.Result.ResultData;
import me.xiongxiao.life.plan.service.TextRExtendService;
import me.xiongxiao.life.plan.util.Log;
import me.xiongxiao.life.plan.util.Time;
import me.xiongxiao.life.plan.verification.Verify;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName FileResource
 * @Desctiption 描述
 * @Author Abear
 * @Date 2019/7/7 11:09
 * @Version 1.0
 **/
@Component
@Path("/file")
public class FileResource {
    @Autowired
    public Log LOGGER;
    @Autowired
    public TextRExtendService tService;
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> hello() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "0");
        map.put("msg", "success");
        return map;
    }
    @GET
    @Path("/name/{filename}/{token}")
    public Response getFile(@PathParam("filename") String filename, @PathParam("token") String token) throws UnsupportedEncodingException {
        filename = URLDecoder.decode(filename, "UTF-8");
        String st = filename.substring(0, 7); // 2019-07-10-xiong.jpg 位置 + 1
        String fileName = filename.substring(9);
        String pathname = "/upload/" + st + "/" + filename;
        File file = new File(pathname);
        LOGGER.i(filename + "  n: " + fileName + " pathname:"+pathname);
        //如果文件不存在,提示404
        if(!file.exists()){
            return Response.status(Response.Status.NOT_FOUND).build();
        }
//        try {
//            filename = URLEncoder.encode("下载测试.xls", "UTF-8");
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
        return Verify.v(token)?Response.status(Response.Status.UNAUTHORIZED).build(): Response
                .ok(file)
                .header("Content-disposition","attachment;filename=" + fileName)
                .header("Cache-Control", "no-cache").build();
    }
    // curl -X POST -F "file=@demo.txt" http://localhost:8081/resource/file
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Path("/upload")
    @Produces(MediaType.APPLICATION_JSON)
    public ResultData upload(@FormDataParam("file") InputStream fis,
                             @FormDataParam("file") FormDataContentDisposition disposition,
                             @Context ServletContext ctx) {
        String year_month = Time.getYearMonth();
        String file_path = "/upload/" + year_month;
        String year_month_day = Time.getYearMonthDay();
        String extension = FilenameUtils.getExtension(disposition.getFileName());
        if(extension.equals("")) return RCM.NO_TYPE();
        String file_name = null;//  String fb =  new String(file_name.getBytes("iso-8859-1"),"UTF-8");//file_name.getBytes("iso-8859-1").toString();
        try {
            file_name = new String(disposition.getFileName().getBytes("iso-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            return RCM.UNSUPPORTED_ENCODING();
        }

        String new_file_name = year_month_day + "-"+ file_name;
        File upload = new File(file_path,new_file_name);
        String path = "/resource/file/name/" + new_file_name;

        try {
            FileUtils.copyInputStreamToFile(fis, upload);
            tService.addEvent(extension, path);
            return new ResultData().success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultData().error();
    }
    @GET
    @Path("/upload/cos")
    public String upload_cos(){
        return "cos html";
    }
}
  • 同步位置:CSDN,简书,静态博客。
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值