strtus2 上传

FileUploadAction.java

package com.tya.base.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

public class FileUploadAction extends BaseAction {
private static final long serialVersionUID = 572146812454l;
private static final int BUFFER_SIZE = 16 * 1024;


@Override
public String execute() {
try {
processRequest(getRequest(),getResponse());
} catch (Exception e) {
e.printStackTrace();
}

return SUCCESS;
}

protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//Struts2  请求 包装过滤器
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;

// 获得上传的文件名
//String fileName = wrapper.getFileNames("imgFile")[0];
String fileName = wrapper.getParameter("Filename");
//获得未见过滤器
File file = wrapper.getFiles("Filedata")[0];
//----------- 重新构建上传文件名----------------------
final Lock lock = new ReentrantLock();
String newName = null;
lock.lock();
try {
//加锁为防止文件名重复
newName = System.currentTimeMillis()
+ fileName.substring(fileName.lastIndexOf("."),
fileName.length());
}finally {
lock.unlock();
}
//------------ 锁结束 -------------
//获取文件输出流
FileOutputStream fos = new FileOutputStream(request.getSession()
.getServletContext().getRealPath("/")
+ "image\\" + newName);
//图片文件地址
String newFileName = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/image/" + newName;
byte[] buffer = new byte[BUFFER_SIZE];
//获取内存中当前文件输入流
InputStream in = new FileInputStream(file);
try {
int num = 0;
while ((num = in.read(buffer)) > 0) {
fos.write(buffer, 0, num);
}
out.println(newFileName);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
in.close();
fos.close();
out.flush();
out.close();
}
}



}

你可能感兴趣的:(java,apache,html,servlet)