java操作文件上传及如何修改File文件的权限
程序员文章站
2022-06-14 22:02:44
使用上传文件的代码如下:private static final int ALLOW_DOWNLOAD_COUNT = 2;private static Map downloadRecordMap = new HashMap();private String barcodeFilePathPrefix="/data/result";/** * * 判断文件是否存在 * *...
使用上传文件的代码如下:
private static final int ALLOW_DOWNLOAD_COUNT = 2;
private static Map<String, Integer> downloadRecordMap = new HashMap<String, Integer>();
private String barcodeFilePathPrefix="/data/result";
/**
*
* 判断文件是否存在
*
*/
@RequestMapping("/sampleFile/exists")
@ResponseBody
public Object existsFile(String fileName) {
File file = new File(barcodeFilePathPrefix, fileName);
if (file.exists()) {
return AjaxResult.RESULT_SUCCESS;
} else {
return AjaxResult.RESULT_ERROR;
}
}
/**
*
* 样本文件上传
*
*/
@RequestMapping("/sampleFile/upload")
@ResponseBody
public Object fileupload(HttpServletRequest request, @RequestParam("sampleFile") CommonsMultipartFile sampleFile) {
AdminUser adminUser = (AdminUser) request.getSession().getAttribute("nowManager");
String name = (adminUser != null ? adminUser.getUsername().toString() : "未登录");
try {
String fileName = sampleFile.getOriginalFilename();
File destfile = new File(barcodeFilePathPrefix, fileName);
SampleFileLog sampleFileLog=new SampleFileLog();
sampleFileLog.setAction("上传文件"+fileName);
sampleFileLog.setOperator(name);
sampleFileLog.setTime(new Date());
logMongoTemplate.save(sampleFileLog);
if (!destfile.exists()) { // 文件不存在
destfile.createNewFile();
copyFile(sampleFile.getInputStream(), destfile);
} else { // 文件存在
copyFile(sampleFile.getInputStream(), destfile);
}
} catch (IOException e) {
e.printStackTrace();
return AjaxResult.resultError(e.getMessage());
}
return AjaxResult.RESULT_SUCCESS;
}
@RequestMapping("/sampleFile/download")
public void fileDownload(HttpServletRequest request, @RequestParam("fileName") String fileName,
HttpServletResponse response) throws IOException {
AdminUser adminUser = (AdminUser) request.getSession().getAttribute("nowManager");
String name = (adminUser != null ? adminUser.getUsername().toString() : "未登录");
SampleFileLog sampleFileLog=new SampleFileLog();
sampleFileLog.setAction("下载文件"+fileName);
sampleFileLog.setOperator(name);
sampleFileLog.setTime(new Date());
logMongoTemplate.save(sampleFileLog);
int i = downloadRecordMap.get(name)==null?0:downloadRecordMap.get(name);
if (i > ALLOW_DOWNLOAD_COUNT) {
response.getWriter()
.println("<!DOCTYPE HTML>\r\n" + "<html>\r\n" + "<head><meta charset=\"utf-8\"> \r\n" + "<title>超过下载次数,请联系管理员</title>\r\n"
+ "</head>\r\n" + "<body>\r\n" + " <h1>超过下载次数,请联系管理员</h1>\r\n" + "</body>\r\n"
+ "</html>\r\n" + "");
return;
}
i = i+1;
downloadRecordMap.put(name, i);
try {
File file = new File(barcodeFilePathPrefix, fileName);
if (file.exists()) {
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
BufferedReader fileInput = new BufferedReader(new FileReader(file));
String line = null;
while (StringUtils.isNotBlank(line = fileInput.readLine())) {
buffer.append(line + "\n");
}
response.getWriter().write(buffer.toString());
fileInput.close();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
response.getWriter().println("<!DOCTYPE HTML>\r\n" + "<html>\r\n" + "<head><meta charset=\"utf-8\">\r\n" + "<title>没找到文件</title>\r\n"
+ "</head>\r\n" + "<body>\r\n" + " <h1>没找到文件</h1>\r\n" + "</body>\r\n" + "</html>\r\n" + "");
}
/**
* 文件复制
*
* @param sourceInputStream
* @param destFile
* @throws IOException
*/
private void copyFile(InputStream sourceInputStream, File destFile) throws IOException {
BufferedReader sourceReader = new BufferedReader(new InputStreamReader(sourceInputStream));
BufferedWriter destWriter = new BufferedWriter(new FileWriter(destFile));
String line = null;
while ((line = sourceReader.readLine()) != null) {
destWriter.write(line);
destWriter.newLine();
}
sourceReader.close();
destWriter.close();
}
可能遇到的问题—上传的文件其他程序和用户无法读取—Permission denied
原因是 调用createNewFile()方法默认的权限是644
在java中修改File权限的几种方式
方案一 使用File的方法
import java.io.File;
2.import java.io.IOException;
public class FilePermission
{
public static void main( String[] args )
{
try {
File file = new File("/home/test3.txt");
if (file.createNewFile()){
System.out.println("File is created!");
file.setExecutable(true);//设置可执行权限
file.setReadable(true);//设置可读权限
file.setWritable(true);//设置可写权限
System.out.println("is execute allow : " + file.canExecute());
System.out.println("is read allow : " + file.canRead());
System.out.println("is write allow : " + file.canWrite());
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();<pre class="java" name="code"></pre>
}
}
方案二 调用系统层面的shell命令chmod运行
Runtime runtime = getRuntime();
String command = "chmod 770 " + dirPath;
try {
Process process = runtime.exec(command);
process.waitFor();
int existValue = process.exitValue();
if(existValue != 0){
logger.log(Level.SEVERE, "Change file permission failed.");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Command execute failed.", e);
}
注意 该使用该方式时,路径值不能包含空格和分号,否则会造成安全风险。如下:
当dirPath带有空格如下:
dirPath = /home/a aa.txt
当我们运行
chmod 770 /home/a aa.txt
实际运行的命令效果等同于
chmod 770 /home/a
chmod 770 aa.txt
/home/a整个目录都会被修改成770权限,不符合预期只修改一个文件。
方案三–NIO方式
private void changeFolderPermission(File dirFile) throws IOException {
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
try {
Path path = Paths.get(dirFile.getAbsolutePath());
Files.setPosixFilePermissions(path, perms);
} catch (Exception e) {
logger.log(Level.SEVERE, "Change folder " + dirFile.getAbsolutePath() + " permission failed.", e);
}
}
参考链接:
https://www.jb51.net/article/167122.htm
本文地址:https://blog.csdn.net/q383965374/article/details/107665282