X5 UI2 attachmentSimple 组件上传文件到本地目录,并下载

X5 提供了组件attachmentSimple 此组件可以自定义文件上传的路径,而不是上传到X5自带的文档中心。

使用组件attachmentSimple,并自定义文件存储Action对应的路径是 “$UI/sybdc/service/simpleFileStore.j” 注意下面代码,项目需求修改了attachmentSimple 的样式,大家自己可以使用自带的组件不修改样式,此处css 代码不上传。"$UI/sybdc/service/simpleFileStore.j" 自己实现上传下载的代码。自己的存放路径都可以在这里处理。

组件代码如下

···

<div component="$UI/system/components/justep/attachment/attachmentSimple" actionUrl="$UI/sybdc/service/simpleFileStore.j" xid="attachmentSimple1" bind-ref='$object.ref("DOCS")'>

            <div class="x-attachment" xid="div3">

              <div class="x-attachment-content x-card-border" xid="div4" style="background-color:#F0F1F4;">

                <div class="x-doc-process" xid="div5">

                  <div class="progress-bar x-doc-process-bar" role="progressbar" style="width:0%;" xid="progressBar1" />

                </div> 

                <div data-bind="foreach:$attachmentItems" xid="div6">

                  <div class="x-attachment-cell" xid="div7">

                    <div class="x-attachment-item x-item-other" data-bind="click:$model.previewOrRemoveItem.bind($model),style:{backgroundImage:($model.previewPicture.bind($model,$object))()}" xid="div8">

                      <a data-bind="visible:$model.$state.get() == 'remove'" class="x-remove-barget" xid="a1" />

                    </div>

                  </div>

                </div> 

                <div class="x-attachment-cell" data-bind="visible:$state.get() == 'upload'" xid="div9">

                  <div class="x-attachment-item x-item-upload" data-bind="visible:$state.get() == 'upload'" xid="div10" ></div>

                </div> 

                <div class="x-attachment-cell" data-bind="visible:$state.get() == 'upload' &amp;&amp; $attachmentItems.get().length &gt; 0" xid="div11">

                  <div class="x-attachment-item x-item-remove" data-bind="click:changeState.bind($object,'remove')" xid="div12" ></div>

                </div> 

                <div style="clear:both;" xid="div13" ><span xid="span1" class="pull-right clearfix" style="margin:-38px 90px 0 0;color:#666666;"><![CDATA[点击上传]]></span></div>

              </div>

            </div>

          </div>

···

simpleFileStore.j 代码如下



```

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.io.FileUtils;

import org.apache.commons.io.IOUtils;

import com.sdjt.sybdc.AppUtils;

public class SimpleFileStore extends com.justep.ui.impl.JProcessorImpl {

static String docStorePath;

static File docStoreDir;

static {

docStorePath = AppUtils.getFileUplaodDir(); //此处文件上传的根路劲在配置文件中定义了

docStoreDir = new File(docStorePath);

}

/**

* get为获取文件 浏览或者下载

**/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String operateType = request.getParameter("operateType");

if ("copy".equals(operateType)) {

copyFile(request, response);

} else {

getFile(request, response);

}

}

private static void copyFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

String ownerID = request.getParameter("ownerID");

String targetOwnerID = request.getParameter("targetOwnerID");

String storeFileName = request.getParameter("storeFileName");

File file = new File(docStorePath + File.separator + ownerID + File.separator + storeFileName);

File targetFile = new File(docStorePath + File.separator + targetOwnerID + File.separator + storeFileName);

FileUtils.copyFile(file, targetFile);

}

private static final int BUFFER_SIZE = 32768 * 8;

private static void getFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

String ownerID = request.getParameter("ownerID");

String realFileName = URLEncoder.encode(request.getParameter("realFileName"), "utf-8");

String storeFileName = request.getParameter("storeFileName");

String operateType = request.getParameter("operateType");

String subPath = request.getParameter("subPath");

/* String fileSize = request.getParameter("fileSize"); */

File file = new File(docStorePath + (subPath != null ? subPath : "") + File.separator + ownerID + File.separator + storeFileName);

FileInputStream fis = new FileInputStream(file);

response.setHeader("Cache-Control", "pre-check=0, post-check=0, max-age=0");

String fileNameKey = "filename";

if ("download".equals(operateType)) {

response.addHeader("Content-Disposition", "attachment; " + fileNameKey + "=\"" + realFileName + "\"");

} else {

response.addHeader("Content-Disposition", "inline; " + fileNameKey + "=\"" + realFileName + "\"");

}

OutputStream os = response.getOutputStream();

byte[] buffer = new byte[BUFFER_SIZE];

try {

int read;

while ((read = fis.read(buffer)) != -1) {

os.write(buffer, 0, read);

}

} finally {

fis.close();

}

}

/**

* post为上传

**/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String contentType = request.getContentType();

try {

if ("application/octet-stream".equals(contentType)) {

storeOctStreamFile(request, response);

} else if (contentType != null && contentType.startsWith("multipart/")) {

storeFile(request, response);

} else {

throw new RuntimeException("not supported contentType");

}

} catch (Exception e) {

e.printStackTrace();

throw new IOException("storeFile异常");

}

response.getWriter().write("");

}

private static void storeOctStreamFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

InputStream in = null;

FileOutputStream storeStream = null;

try {

String ownerID = request.getParameter("ownerID");

String storeFileName = request.getParameter("storeFileName");

String subPath = request.getParameter("subPath");

in = request.getInputStream();

String storePath = docStorePath + (subPath != null ? subPath : "") + File.separator + ownerID;

getOrCreateFile(storePath);

File toStoreFile = new File(storePath + File.separator + storeFileName);

storeStream = new FileOutputStream(toStoreFile);

IOUtils.copy(in, storeStream);

} finally {

IOUtils.closeQuietly(in);

IOUtils.closeQuietly(storeStream);

}

}

private static File getOrCreateFile(String path) {

File storeDir = new File(path);

if (!(storeDir.exists() && storeDir.isDirectory())) {

storeDir.mkdirs();

}

return storeDir;

}

public static List<FileItem> parseMultipartRequest(HttpServletRequest request) throws FileUploadException {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletContext servletContext = request.getSession().getServletContext();

File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

factory.setRepository(repository);

// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request

@SuppressWarnings("unchecked")

List<FileItem> items = upload.parseRequest(request);

return items;

}

private static void storeFile(HttpServletRequest request, HttpServletResponse response) throws Exception {

String subPath = request.getParameter("subPath");

HashMap<String, String> params = new HashMap<String, String>();

List<FileItem> items = parseMultipartRequest(request);

Iterator<FileItem> iter = items.iterator();

FileItem fileItem = null;

while (iter.hasNext()) {

FileItem item = iter.next();

if (item.isFormField()) {

String name = item.getFieldName();

String value = item.getString();

params.put(name, value);

} else {

fileItem = item;

}

}

if (fileItem != null) {

String storePath = docStorePath + (subPath != null ? subPath : "") + File.separator + params.get("ownerID");

File storeDir = new File(storePath);

if (!(storeDir.exists() && storeDir.isDirectory())) {

storeDir.mkdirs();

}

File toStoreFile = new File(storePath + File.separator + params.get("storeFileName"));

fileItem.write(toStoreFile);

}

}

}

```

类 AppUtils.java



```

package com.sdjt.sybdc;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashSet;

import java.util.Properties;

import java.util.Set;

import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSONObject;

import com.justep.filesystem.FileSystemWrapper;

public class AppUtils {

private static Properties appProperties;

private static Set<String> securityAccess = new HashSet<String>();

static {

File file = new File(FileSystemWrapper.instance().getRealPath("/UI2/sybdc/config/app.properties"));

appProperties = new Properties();

InputStream in = null;

try {

in = new FileInputStream(file);

appProperties.load(in);

} catch (Exception ex) {

ex.printStackTrace();

System.exit(1);

} finally {

if (in != null)

try {

in.close();

} catch (IOException e) {

}

}

}

public static Properties getAppProperties() {

return appProperties;

}

public static String getBizServiceUrl() {

return appProperties.getProperty("bizServiceUrl");

}

public static boolean isSecurityService(String action) {

for (String regex : securityAccess) {

if (regex != null && regex.trim().length() > 0 && action.matches(regex)) {

return true;

}

}

return false;

}

public static String getYwsbDataDir() {

return appProperties.getProperty("ywsbDataDir");

}

public static String getFileUplaodDir() {

return appProperties.getProperty("fileUplaodDir");

}

public static String getDateDir() {

return new SimpleDateFormat("/yyyy/MM/dd/HH").format(new Date(System.currentTimeMillis()));

}

public static String getDateDir(long timestamp) {

return new SimpleDateFormat("/yyyy/MM/dd/HH").format(new Date(timestamp));

}

public static JSONObject success(Object data) {

JSONObject ret = new JSONObject();

ret.put("flag", true);

ret.put("data", data);

return ret;

}

public static JSONObject error(String message) {

JSONObject ret = new JSONObject();

ret.put("flag", false);

ret.put("message", message);

return ret;

}

public static String saveTempFile(InputStream in) throws IOException {

String path = AppUtils.getDateDir() + "/" + UUID.randomUUID().toString();

File file = new File((String) AppUtils.getAppProperties().get("tempDir"), path);

file.getParentFile().mkdirs();

FileOutputStream output = new FileOutputStream(file);

IOUtils.copy(in, output);

IOUtils.closeQuietly(output);

return path;

}

public static void downLoadFile(String filePath, String fileName, HttpServletResponse response) throws IOException {

response.setHeader("Pragma", "public");

response.setHeader("Cache-Control", "pre-check=0, post-check=0, max-age=0");

response.setHeader("Content-Transfer-Encoding", "binary");

response.setDateHeader("Expires", 0);

response.setHeader("Content-Type", "application/pdf");

if (fileName != null) {

fileName = java.net.URLEncoder.encode(fileName, "UTF8");

response.addHeader("Content-disposition", "attachment;filename=\"" + fileName + "\";");

}

File file = new File((String) AppUtils.getAppProperties().get("tempDir"), filePath);

response.setHeader("Content-Length", file.length() + "");

FileInputStream input = new FileInputStream(file);

response.getOutputStream().write(IOUtils.toByteArray(input));

IOUtils.closeQuietly(input);

}

}

```


/UI2/sybdc/config/app.properties 配置文件内容如下:



```

fileUplaodDir=d:/ywsb/file

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342