📄 bookadd.java
字号:
package action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.bean.Tbook;
import com.dao.BookDAO;
import com.opensymphony.xwork2.ActionSupport;
/**
*
* 进行书籍增加操作action
*
*/
public class BookAdd extends ActionSupport {
private static final long serialVersionUID = 572146812454l;
private static final int BUFFER_SIZE = 16 * 1024;
private Tbook tbook;
private String msg;
private File myFile;
private String fileName;
private String contentType;
private String imageFileName;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Tbook getTbook() {
return tbook;
}
public void setTbook(Tbook tbook) {
this.tbook = tbook;
}
/**
* 将文件复制到项目的imgs文件夹下
*/
public static void copy(File upFile, File downFile) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(upFile),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(downFile),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
try {
imageFileName = new Date().getTime() + getExtention(fileName);
File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/imgs") + "/" + imageFileName);
copy(myFile, imageFile);
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("文件的名称:" + imageFileName);
if (null != imageFileName) {
tbook.setBookimg(imageFileName);
}
if (!new BookDAO().addBook(tbook)) {
msg = "添加书籍<<" + tbook.getBookname() + ">>失败!请检查输入的信息是否错误!";
return ERROR;
}
msg = "添加书籍<<" + tbook.getBookname() + ">>成功!";
return SUCCESS;
}
public String getMyFileFileName() {
return fileName;
}
public String getMyFileContentType() {
return contentType;
}
public void setMyFileContentType(String contentType) {
this.contentType = contentType;
}
public void setMyFileFileName(String fileName) {
this.fileName = fileName;
}
public String getImageFileName() {
return imageFileName;
}
public String getContentType() {
return contentType;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -