仅供参考
package rest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
@Path("downUploadRest")
public class DownUploadRest {
DownloadService downloadService=(DownloadService) ApplicationContext.getBean("downloadService");
/**
* 按车辆类型加载图片
* @param typeid
* @param request
* @param response
* @return
* @throws UnsupportedEncodingException
*/
@GET
@Path("getCar/{typeid}")
@Produces(MediaType.TEXT_PLAIN)
public String downloadFile(@PathParam("typeid") String typeid,@Context HttpServletRequest request, @Context HttpServletResponse response) throws UnsupportedEncodingException {
Dto dto1 = new BaseDto();
dto1.put("typeid", typeid);
Dto dto=new BaseDto();
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
Boolean isOnLine = true; //是否在线浏览
// String path1=dto.getAsString("ATTACHPATH");
String pathat=DictConstants.upload_paht;
String path1= pathat + "\\" +"IMG_20160406_185746.jpg";
File file = new File(path1.toString());
FileInputStream fis = null;
BufferedInputStream buff = null;
OutputStream myout = null;
try {
if (!file.exists()) {
//ServletActionContext.getResponse().sendError(404, "File not found!");
return "nofile";
}
response.reset();
if (isOnLine) { //在线打开方式
URL u = new URL("file:///" + path1.toString());
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ new String(file.getName().getBytes("gbk"), "iso-8859-1"));
} else { //纯下载方式
//设置response的编码方式
response.setContentType("application/x-msdownload");
//写明要下载的文件的大小
response.setContentLength((int) file.length());
//设置附加文件名(解决中文乱码)
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
}
fis = new FileInputStream(file);
buff = new BufferedInputStream(fis);
byte[] b = new byte[10240];//相当于我们的缓存
long k = 0;//该值用于计算当前实际下载了多少字节
//从response对象中得到输出流,准备下载
myout = response.getOutputStream();
while (k < file.length()) {
int j = buff.read(b, 0, 10240);
k += j;
//将b中的数据写到客户端的内存
myout.write(b, 0, j);
}
//将写入到客户端的内存的数据,刷新到磁盘
myout.flush();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (buff != null)
buff.close();
if (myout != null)
myout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 身份证、驾照文件上传
* @param
* @return
* @throws IOException
*/
@POST
@Path("uploadid/{type}")
@Consumes( { MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
@Produces(MediaType.TEXT_PLAIN)
public JSONObject upload(@PathParam("type") String type, @Context HttpServletRequest request, @Context
HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
String msg = "上传失败!";
Boolean flag=false;
Map<String, String> map= new HashMap<String, String>();
String objectNameStr = "";
String docbelongStr="";
String fileName="";
String fileFormat="";
String saveFilePath="";
String fileNewName="";
String attId="";
String fieldNameId="";
String pathat=DictConstants.upload_paht;
JSONObject oo = new JSONObject();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// 构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8"); // 支持中文文件名
List list = new ArrayList<FileItem>();
try {
// 解析表单中提交的所有文件内容
list = upload.parseRequest(request);
for (int i = 0; i < list.size(); i++) {
FileItem item = (FileItem) list.get(i);
if(item.isFormField()){ //普通表单值
map.put(item.getFieldName(), item.getString("UTF-8"));
}else {
String name = item.getName(); //获得上传的文件名(IE上是文件全路径,火狐等浏览器仅文件名)
fieldNameId= item.getFieldName();
fileName = name.substring(
name.lastIndexOf('\\') + 1, name.length());
fileFormat=fileName.substring(fileName.lastIndexOf(".")); //文件扩展名
objectNameStr = map.get("objectName"); //实体id
docbelongStr = map.get("docbelong"); //文件归属
String uuidStr = UUID.randomUUID().toString();
fileNewName=uuidStr+fileFormat;
flag=upload4Stream(fileNewName, pathat, item.getInputStream()); //上传文件
if(flag){
msg = "上传成功!";
}
}
}
PubMemberAttach att=new PubMemberAttach();
String user=null;
String uuidStr = UUID.randomUUID().toString();
att.setAttachId(uuidStr);
att.setAttachname(fileNewName);
att.setAttachpath(pathat+"\\"+fileNewName);
att.setMemberId(user);
att.setCreateDate(new Date().toString());
int i=0;
try {
i = downloadService.addMemberAtt(att);
if (i == 1) {
oo.put("status", "200");
} else {
oo.put("status", "400");
}
} catch (Exception e) {
oo.put("status", "400");
}
attId=uuidStr;
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("application/json;charset=UTF-8");
try {
oo.put("serverPath","133");
// oo.put("code",1);
// oo.put("img",attId);
} catch (JSONException e) {
e.printStackTrace();
}
return oo;
}
/**
* 上传文件具体操作
* @param fileName 文件名
* @param filePath 文件上传路径
* @param inStream 文件流
* @return 上传是否成功
*/
private boolean upload4Stream(String fileName, String filePath,
InputStream inStream) {
boolean result = false;
if ((filePath == null) || (filePath.trim().length() == 0)) {
return result;
}
OutputStream outStream = null;
try {
String wholeFilePath = filePath + "\\" + fileName;
System.out.println(wholeFilePath);
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
File outputFile = new File(wholeFilePath);
boolean isFileExist = outputFile.exists();
boolean canUpload = true;
if (isFileExist) {
canUpload = outputFile.delete();
}
if (canUpload) {
int available = 0;
outStream = new BufferedOutputStream(new FileOutputStream(
outputFile), 2048);
byte[] buffer = new byte[2048];
while ((available = inStream.read(buffer)) > 0) {
if (available < 2048)
outStream.write(buffer, 0, available);
else {
outStream.write(buffer, 0, 2048);
}
}
result = true;
}
} catch (Exception e) {
e.printStackTrace();
try {
if (inStream != null) {
inStream.close();
}
if (outStream != null)
outStream.close();
} catch (Exception ex) {
e.printStackTrace();
}
} finally {
try {
if (inStream != null) {
inStream.close();
}
if (outStream != null)
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result);
return result;
}
}