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

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。