上岛上咖啡 2015-05-19 02:17 采纳率: 100%
浏览 28360
已采纳

MultipartFile上传文件时,中文文件名乱码怎么解决?

package com.upload;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class UploadContronller {

@RequestMapping("/toUpload.shtml")

public String toUpload(){

    return "upload";

}

@RequestMapping(value="/upload.shtml")

public String upload(@RequestParam(value="file",required=false)CommonsMultipartFile file,

        HttpServletRequest request,ModelMap model) throws Throwable{

// request.setCharacterEncoding("UTF-8");

    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }

// String type=file.getContentType();

    //获取存储路径
    String path=request.getSession().getServletContext().getRealPath("upload");

    //上传文件名称
    String fileName=file.getOriginalFilename();

    System.out.println(fileName);

    //转义拆分重命名文件
    String[] strArr=fileName.split("\\.");

    System.out.println(strArr[0]);

    System.out.println(strArr[1]);

    SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMDDHHmmss");

    String strName=sdf.format(new Date());

    fileName=strName+"."+strArr[1];

    System.out.println("------文件路径:"+path);

    //创建存储目录
    File targetFile=new File(path,fileName.toString());

    if(!targetFile.exists()){
        targetFile.mkdirs();
    }

    //文件上传
    try {

        file.transferTo(targetFile);

        //将文件路径转发到页面
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);

    } catch (IllegalStateException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    return "result";
}

}

  • 写回答

5条回答

  • 黄金刺 2015-05-19 02:41
    关注
    try {
        fileName = new String(fileName.getBytes(), "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统