文件上传统一处理工具类。
Spring MVC 提供了MultipartFile
类来接收文件对象。
文件上传类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import java.io.File;
import javax.servlet.http.HttpServletRequest; import org.springframework.web.multipart.MultipartFile;
public class UploadImg {
public static String uploadImage(HttpServletRequest request, MultipartFile file) throws Exception { String path = request.getServletContext().getRealPath("updown/images");
String filename = file.getOriginalFilename();
String suffix = FileSuffix.getSuffix(filename);
String newFileName = RandomID.getRandomID() + suffix;
file.transferTo(new File(path + File.separator + newFileName));
String imgSavePath = File.separator + "updown" + File.separator + "images" + File.separator + newFileName;
return imgSavePath; } }
|
文件后辍名类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import java.io.File;
public class FileSuffix {
public static String getSuffix(String filename){ File file = new File(filename); String fileName = file.getName(); String suffix = fileName.substring(fileName.lastIndexOf(".")); return suffix; }
public static String getSuffixWithoutPoint(String filename){ File file = new File(filename); String fileName = file.getName(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); return suffix; } }
|