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";
}

}

查看全部
u013471469
上岛上咖啡
2015/05/19 02:17
  • multipart ile
  • 乱码
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

5个回复