log檔顯示在153行的時後報錯,但一直找不到錯誤。只知道錯誤在setPosixFilePermissions這一行。
系統是在linux中執行的。
檔案的路徑為/opt/ops/web/webapps/ROOT/attachment/1624602442378/key4_lic
希望大家能給點方向。
找到的答案:
OutputStream out = Files.newOutputStream(file);往上移就行了。
OutputStream 會產生一個空檔案,那時就有路徑了。
log檔
2021-06-26 08:54:53 ERROR FileUpload2:150 - file: /opt/ops/web/webapps/ROOT/attachment/1624602442378/key4_lic
2021-06-26 08:54:53 ERROR FileUpload2:151 - perms: [OTHERS_READ, OWNER_READ, OWNER_WRITE, GROUP_WRITE, GROUP_READ]
2021-06-26 08:54:53 ERROR FileUpload2:183 - STATUS: Failure(/opt/ops/web/webapps/ROOT/attachment/1624602442378/key4_licjava.nio.file.NoSuchFileException:
/opt/ops/web/webapps/ROOT/attachment/1624602442378/key4_lic
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileAttributeViews$Posix.setMode(UnixFileAttributeViews.java:238)
at sun.nio.fs.UnixFileAttributeViews$Posix.setPermissions(UnixFileAttributeViews.java:260)
at java.nio.file.Files.setPosixFilePermissions(Files.java:2045)
at ops.servlet.FileUpload2.doGet(FileUpload2.java:153)
at ops.servlet.FileUpload2.doPost(FileUpload2.java:209)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
完整程式
package ops.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import ops.service.OPSService;
import system.common.Configurator;
import system.db.UserlogSQL;
import system.db.bean.UserBean;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* 處理上傳檔案(目前用在公告附件)
*/
public class FileUpload2 extends HttpServlet {
private static final long serialVersionUID = -7215302089706068618L;
private static final Logger logger = Logger.getLogger(FileUpload2.class);
public static final String lock = "lock";
// Initialize global variables
public void init() throws ServletException {
}
// Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
synchronized (lock) {
String status = "Failure";
String clientIP = request.getRemoteAddr();
UserBean userBean = null;
HttpSession httpsession = request.getSession(false);
//log4j
Properties props = new Properties();
props.put("log4j.rootLogger", "error, consoleout, fileout");
props.put("log4j.appender.consoleout", "org.apache.log4j.ConsoleAppender");
props.put("log4j.appender.consoleout.layout", "org.apache.log4j.PatternLayout");
props.put("log4j.appender.fileout", "org.apache.log4j.RollingFileAppender");
props.put("log4j.appender.fileout.MaxFileSize", "5MB");
props.put("log4j.appender.fileout.MaxBackupIndex", "10");
props.put("log4j.appender.fileout.layout", "org.apache.log4j.PatternLayout");
props.put("log4j.appender.fileout.layout.ConversionPattern", "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");
if(Configurator.osType > 0) {
props.put("log4j.appender.fileout.File", "/opt/ops/web/logs/FileUpload2.log");
}else {
props.put("log4j.appender.fileout.File", "d:/testlogs/myapp.log");
}
//傳入log4j.properties路徑
PropertyConfigurator.configure(props);
if (httpsession != null) {
userBean = (UserBean) httpsession.getAttribute("userBean");
}
if (userBean != null) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
Path delFile = null;
try {
// FileItemIterator items1 =
// upload.getItemIterator(request);
// System.out.println(items1.hasNext());
Iterator<Entry<String, List<FileItem>>> iter = upload.parseParameterMap(request).entrySet()
.iterator();
while (iter.hasNext()) {
Entry<String, List<FileItem>> entry = iter.next();
List<FileItem> items = entry.getValue();
for (int i = 0; i < items.size(); i++) {
FileItem fi = items.get(i);
logger.error("fi: "+fi.toString());
// System.out.println(entry.getKey() + " " + fi.isFormField() + " " + fi.getName() + " "
// + fi.getFieldName());
// }
// }
//
// List<FileItem> items = upload
// .parseRequest((RequestContext) request);
// Iterator<FileItem> iter = items.iterator();
// while (iter.hasNext()) {
// FileItem fi = (FileItem) iter.next();
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
Path file = null;
String item = null;
// System.out.println("FileUpload="+fieldName);
if (fieldName.startsWith("ann_")) {
item = "menu.Announcement";
String[] lang = fieldName.split("_");
if (lang.length == 2) {
String strPath=OPSService.attPath.replace("\\\\","\\");
file = Paths.get(strPath + lang[1]+File.separator+fi.getName());
delFile = file.getParent();
if (Files.exists(delFile)) {
File dir = delFile.toFile();
File[] list = dir.listFiles();
for(int j=0;j<list.length;j++){
list[j].delete();
}
dir.delete();
}
Files.createDirectory(delFile);
}
}
if (file != null) {
if (Configurator.osType > 0) {
Set<PosixFilePermission> perms;
perms = new HashSet<PosixFilePermission>();
// add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
logger.error("file: "+file);
logger.error("perms: "+perms.toString());
Files.setPosixFilePermissions(file, perms);
}
OutputStream out = Files.newOutputStream(file);
byte[] data = new byte[1000000];
InputStream in = fi.getInputStream();
int readCount = 0;
while ((readCount = in.read(data)) > 0) {
// System.out.println("readCount=" +
// readCount);
out.write(data, 0, readCount);
}
in.close();
out.close();
fi.delete();
status = "Success";
}
UserlogSQL.saveLog(userBean.userName, clientIP, item, "Import", status,
"filename="+fi.getName());
logger.error("STATUS: "+status);
}
fi.delete();
}
}
} catch (Exception e) {
//將整個軌跡轉成文字檔,在LOG顯示。
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String printStackTrace = writer.toString();
status = status + "(" + e.getMessage() + printStackTrace+ ")";
logger.error("STATUS: "+status); //debug層級
System.out.println("status:"+status);
if(delFile!=null){
if(Files.isDirectory(delFile)){
File dir = delFile.toFile();
File[] list = dir.listFiles();
for(int j=0;j<list.length;j++){
list[j].delete();
}
dir.delete();
}
System.out.println("delFile:"+delFile);
//Files.delete(delFile);
Files.deleteIfExists(delFile);
}
}
response.getWriter().print(status);
}else {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
錯誤訊息裡有NoSuchFileException:/opt/ops/web/webapps/ROOT/attachment/1624602442378/key4_lic
會不會是沒有 key4_lic 這個檔案?