no.dusken.aranea.admin.control.UploadFileController.java Source code

Java tutorial

Introduction

Here is the source code for no.dusken.aranea.admin.control.UploadFileController.java

Source

/*
 Copyright 2006 - 2010 Under Dusken
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
     http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

package no.dusken.aranea.admin.control;

import no.dusken.aranea.view.EmptyView;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * Used to upload files from the server. No form is needed, since a POST request is created
 * directly by the client
 * <p/>
 * The Image object should be saved AFTER the file upload
 */
public class UploadFileController extends SimpleFormController {

    private String resourceDir;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {
        // There is no backing object, but we cannot return null..
        return new Object();
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
            BindException bindException) throws Exception {

        String url = ServletRequestUtils.getRequiredStringParameter(request, "imageUrl");

        // get the uploaded file
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (file == null) {
            // There is no file. Exit
            log.error("Could not extract file from request");
            return new ModelAndView(new EmptyView());
        }
        // transfer the file to a temporary location
        String originalName = file.getOriginalFilename();
        log.debug("Got file: {}", originalName);
        File tmpFile = new File(resourceDir + "/images/tmp/" + originalName);
        tmpFile.getParentFile().mkdirs();
        file.transferTo(tmpFile);

        // move the file to the final destination
        File newFile = new File(resourceDir + "/images/" + url);
        newFile.getParentFile().mkdirs();
        FileUtils.moveFile(tmpFile, newFile);
        // SUCCESS!
        response.setStatus(200);

        return new ModelAndView(new EmptyView());
    }

    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);
        // to actually be able to convert Multipart instance to byte[]
        // we have to register a custom editor
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
        // binder.setBindEmptyMultipartFiles(false);
        // now Spring knows how to handle multipart object and convert them
    }

    @Required
    public void setResourceDir(String resourceDir) {
        this.resourceDir = resourceDir;
    }
}